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 character varying(64) NOT NULL, employee_id character varying(64) NOT NULL UNIQUE, first_name character varying(128) NOT NULL, last_name character varying(128) NOT NULL, license_number character varying(64) NOT NULL UNIQUE, license_expiry_date date NOT NULL, contact_number character varying(32), email character varying(128) UNIQUE, hire_date date NOT NULL, status character varying(32) NOT NULL, PRIMARY KEY (driver_id) )
CREATE TABLE transportation.routes ( route_id character varying(64) NOT NULL, route_number character varying(32) NOT NULL UNIQUE, description text, origin_location_id character varying(64) NOT NULL, destination_location_id character varying(64) NOT NULL, distance_km numeric(10, 2), estimated_duration_minutes integer, type character varying(32) NOT NULL, PRIMARY KEY (route_id) )
CREATE TABLE transportation.locations ( location_id character varying(64) NOT NULL, name character varying(255) NOT NULL, type character varying(64) NOT NULL, address_line1 character varying(255), city character varying(128), state_province character varying(128), postal_code character varying(32), country character varying(64) NOT NULL, latitude numeric(9, 6), longitude numeric(9, 6), timezone character varying(64), PRIMARY KEY (location_id) )
CREATE TABLE transportation.maintenance_logs ( log_id character varying(64) NOT NULL, vehicle_id character varying(64) NOT NULL, service_date date NOT NULL, odometer_reading integer, service_type character varying(128) NOT NULL, description text NOT NULL, cost numeric(10, 2), mechanic_name character varying(128), next_service_due_date date, PRIMARY KEY (log_id) )
CREATE TABLE transportation.bookings ( booking_id character varying(64) NOT NULL, passenger_id character varying(64) NOT NULL, trip_id character varying(64) NOT NULL, seat_number character varying(16), booking_time timestamp with time zone NOT NULL, status character varying(32) NOT NULL, fare numeric(10, 2) NOT NULL, payment_transaction_id character varying(128), special_requests text, PRIMARY KEY (booking_id) )
##Table Structure
CREATE TABLE transportation.locations ( location_id text PRIMARY KEY, name text, type text, address_line1 text, city text, state_province text, postal_code text, country text, latitude numeric, longitude numeric, timezone text )
##Table Structure
CREATE TABLE healthcare.insurance_plans ( plan_id text PRIMARY KEY, plan_name text, insurance_provider text, plan_type text, contact_phone text, website text )
##Table Structure
CREATE TABLE insurance.agents ( agent_id text PRIMARY KEY, first_name text, last_name text, agency_name text, license_number text, license_state text, contact_email text, contact_phone text, hire_date date, termination_date date, status text, commission_rate numeric, manager_id text )
##Table Structure
CREATE TABLE healthcare.diagnoses (
    diagnosis_id character varying(64) NOT NULL, -- unique identifier for the diagnosis entry
    record_id character varying(64) NOT NULL, -- FK linking to the specific medical record entry
    patient_id character varying(64) NOT NULL, -- FK to patients table
    doctor_id character varying(64) NOT NULL, -- FK to doctors table (diagnosing doctor)
    diagnosis_code character varying(20) NOT NULL, -- standard code (e.g., ICD-10)
    code_type character varying(10) NOT NULL DEFAULT 'ICD-10', -- type of code used
    description text, -- textual description of the diagnosis
    diagnosis_date date NOT NULL, -- date the diagnosis was made
    status character varying(32) NOT NULL, -- e.g., Active, Resolved, Ruled Out
    is_chronic boolean DEFAULT false, -- flag for chronic conditions
    PRIMARY KEY (diagnosis_id)
)
##Table Structure
CREATE TABLE 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.claim_documents ( document_id text, claim_id text, document_type text, file_name text, file_path text, file_size_bytes integer, mime_type text, uploaded_by text, uploaded_at timestamp, description text )

[User] For each booking, show the booking_id, seat_number, fare, and the city of the origin location for the trip that was booked.

[Assistant]
SELECT b.booking_id, b.seat_number, b.fare, orig.city AS origin_city
FROM transportation.bookings b
JOIN transportation.trips t ON b.trip_id = t.trip_id
JOIN transportation.routes r ON t.route_id = r.route_id
JOIN transportation.locations orig ON r.origin_location_id = orig.location_id;

[User] Can you show me the name, city, and type for all locations that are in the same city but have different types?

[Assistant] SELECT l1.name, l1.city, l1.type FROM transportation.locations l1 JOIN transportation.locations l2 ON l1.city = l2.city AND l1.location_id <> l2.location_id AND l1.type <> l2.type;

[User] Please only include locations where the city is 'Chicago'.

[Assistant] SELECT l1.name, l1.city, l1.type FROM transportation.locations l1 JOIN transportation.locations l2 ON l1.city = l2.city AND l1.location_id <> l2.location_id AND l1.type <> l2.type WHERE l1.city = 'Chicago';

[User] Show me all pairs of plans offered by the same insurance provider but of different plan types, including the provider name, first plan ID and type, and second plan ID and type.

[Assistant]
SELECT a.insurance_provider,
       a.plan_id AS plan_id_1,
       a.plan_type AS type_1,
       b.plan_id AS plan_id_2,
       b.plan_type AS type_2
FROM healthcare.insurance_plans a
JOIN healthcare.insurance_plans b
  ON a.insurance_provider = b.insurance_provider
 AND a.plan_type <> b.plan_type
 AND a.plan_id < b.plan_id;

[User] Can you restrict this to only those providers that offer at least three distinct plan types?

[Assistant]
SELECT a.insurance_provider,
       a.plan_id AS plan_id_1,
       a.plan_type AS type_1,
       b.plan_id AS plan_id_2,
       b.plan_type AS type_2
FROM healthcare.insurance_plans a
JOIN healthcare.insurance_plans b
  ON a.insurance_provider = b.insurance_provider
 AND a.plan_type <> b.plan_type
 AND a.plan_id < b.plan_id
WHERE a.insurance_provider IN (
  SELECT insurance_provider
  FROM healthcare.insurance_plans
  GROUP BY insurance_provider
  HAVING COUNT(DISTINCT plan_type) >= 3
);

[User] Find agents whose commission_rate is higher than their manager's commission_rate. Show agent_id, agent first_name, agent last_name, commission_rate, manager_id, and the manager's commission_rate.

[Assistant]
SELECT a.agent_id,
       a.first_name,
       a.last_name,
       a.commission_rate,
       a.manager_id,
       m.commission_rate AS manager_commission_rate
  FROM insurance.agents a
  JOIN insurance.agents m
    ON a.manager_id = m.agent_id
 WHERE a.commission_rate > m.commission_rate;

[User] Now restrict to agents hired before January 1, 2023.

[Assistant]
SELECT a.agent_id,
       a.first_name,
       a.last_name,
       a.commission_rate,
       a.manager_id,
       m.commission_rate AS manager_commission_rate
  FROM insurance.agents a
  JOIN insurance.agents m
    ON a.manager_id = m.agent_id
 WHERE a.commission_rate > m.commission_rate
   AND a.hire_date < '2023-01-01';

[User] Find the diagnosis code and description for all non-chronic diagnoses for patient 'patient_789' made by doctor 'doctor_abc'.

[Assistant] SELECT diagnosis_code, description FROM healthcare.diagnoses WHERE patient_id = 'patient_789' AND doctor_id = 'doctor_abc' AND is_chronic = false;

[User] List all unique policies that have claim documents of type 'Claim Form'. For each, return the policy_number, start_date, end_date, and the document file_name.

[Assistant]
SELECT DISTINCT p.policy_number, p.start_date, p.end_date, cd.file_name
FROM insurance.policies p
JOIN insurance.claim_documents cd ON p.policy_id = cd.claim_id
WHERE cd.document_type = 'Claim Form';


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement. ##Table Structure
CREATE TABLE government_services.citizens ( citizen_id text PRIMARY KEY, national_id_number text, first_name text, last_name text, date_of_birth date, gender text, primary_address text, contact_email text, contact_phone text, registration_date timestamp, is_verified boolean )
CREATE TABLE government_services.services ( service_id 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.documents (
    document_id character varying(64) NOT NULL, -- unique identifier for the document instance
    application_id character varying(64), -- FK to applications table (optional, could be linked to citizen directly)
    citizen_id character varying(64) NOT NULL, -- FK to citizens table
    document_type character varying(100) NOT NULL, -- e.g., Passport Scan, Proof of Address, Birth Certificate
    file_reference text NOT NULL, -- reference to the stored file (e.g., S3 URL, internal path)
    upload_timestamp timestamp NOT NULL,
    expiry_date date,
    verification_status character varying(30) DEFAULT 'Pending', -- e.g., Pending, Verified, Rejected
    verified_by_employee_id character varying(64), -- FK to employees table
    verification_timestamp timestamp,
    PRIMARY KEY (document_id)
)
CREATE TABLE government_services.service_locations ( location_id character varying(64) NOT NULL, agency_id character varying(64) NOT NULL, location_name character varying(200), address text NOT NULL, city character varying(100), state character varying(50), postal_code character varying(20), latitude numeric(9, 6), longitude numeric(9, 6), operating_hours text, contact_phone character varying(32), is_accessible boolean, PRIMARY KEY (location_id) )
CREATE TABLE government_services.appointments (
    appointment_id character varying(64) NOT NULL, -- unique identifier for the appointment
    citizen_id character varying(64) NOT NULL, -- FK to citizens table
    employee_id character varying(64), -- FK to employees table (optional, if assigned)
    location_id character varying(64), -- FK to service_locations table (if physical)
    service_id character varying(64), -- FK to services table (optional, if related to specific service)
    scheduled_start_time timestamp NOT NULL,
    scheduled_end_time timestamp,
    purpose text NOT NULL, -- reason for the appointment
    status character varying(30) NOT NULL, -- e.g., Scheduled, Completed, Cancelled, No-Show
    booking_method character varying(50), -- e.g., Online, Phone, In-Person
    created_at timestamp NOT NULL, -- when the appointment was booked
    notes text,
    PRIMARY KEY (appointment_id)
)
CREATE TABLE government_services.notifications ( notification_id text PRIMARY KEY, citizen_id text, application_id text, message_subject text, message_body text, channel text, sent_at timestamp, status text, related_entity_type text, related_entity_id text )
##Table Structure
CREATE TABLE financial_services.customers ( customer_id.text, first_name.text, last_name.text, date_of_birth.date, ssn_hash.text, address.text, city.text, state.text, zip_code.text, country.text, email.text, phone_number.text, created_at.timestamp, status.text, risk_profile.text )
CREATE TABLE financial_services.accounts (
    account_id character varying(64) NOT NULL, -- unique identifier for the account
    customer_id character varying(64) NOT NULL, -- foreign key linking to the customer
    account_number character varying(128) NOT NULL UNIQUE, -- unique account number visible to customer
    account_type character varying(50) NOT NULL, -- e.g., Checking, Savings, Investment, Loan, Credit Card
    balance numeric(19, 4) NOT NULL DEFAULT 0.00, -- current account balance
    currency character varying(3) NOT NULL, -- currency code (e.g., USD, EUR)
    opened_date date NOT NULL, -- date the account was opened
    status character varying(32) NOT NULL, -- e.g., Open, Closed, Frozen
    interest_rate numeric(5, 4), -- annual interest rate, if applicable
    last_updated_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, -- timestamp of last account update
    PRIMARY KEY (account_id),
    FOREIGN KEY (customer_id) REFERENCES financial_services.customers(customer_id)
)
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.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 )
##Table Structure
CREATE TABLE financial_services.accounts ( account_id text PRIMARY KEY, customer_id text, account_number text, account_type text, balance numeric, currency text, opened_date date, status text, interest_rate numeric, last_updated_at timestamp )
##Table Structure
CREATE TABLE government_services.applications ( application_id text, citizen_id text, service_id text, submitted_at timestamp, status text, last_updated_at timestamp, assigned_employee_id text, decision_date date, notes text, reference_number text )

[User] List the service_id, service_name, and agency_id for all active services that have an online application URL provided.

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

[User] Which customers have accounts in more than one state? Please show their customer_id, full name, and the list of states where they hold accounts.

[Assistant]
SELECT c.customer_id, c.first_name || ' ' || c.last_name AS full_name, STRING_AGG(DISTINCT c.state, ', ') AS states
FROM financial_services.customers c
JOIN financial_services.accounts a ON c.customer_id = a.customer_id
GROUP BY c.customer_id, c.first_name, c.last_name
HAVING COUNT(DISTINCT c.state) > 1;

[User] Can you also include the total number of accounts each customer has?

[Assistant]
SELECT c.customer_id, c.first_name || ' ' || c.last_name AS full_name, STRING_AGG(DISTINCT c.state, ', ') AS states, COUNT(a.account_id) AS total_accounts
FROM financial_services.customers c
JOIN financial_services.accounts a ON c.customer_id = a.customer_id
GROUP BY c.customer_id, c.first_name, c.last_name
HAVING COUNT(DISTINCT c.state) > 1;

[User] It seems like it's listing the customer state info rather than the account's. Can you instead show which states are associated with their accounts' addresses?

[Assistant]
SELECT c.customer_id, c.first_name || ' ' || c.last_name AS full_name, STRING_AGG(DISTINCT ca.state, ', ') AS account_states, COUNT(a.account_id) AS total_accounts
FROM financial_services.customers c
JOIN financial_services.accounts a ON c.customer_id = a.customer_id
JOIN financial_services.customers ca ON ca.customer_id = a.customer_id
GROUP BY c.customer_id, c.first_name, c.last_name
HAVING COUNT(DISTINCT ca.state) > 1;

[User] Actually, can you pull the state value from the accounts table instead if possible?

[Assistant]
-- Assuming accounts table has a 'state' field, otherwise this cannot be done directly as accounts does not have state info per schema.
-- If not, we must take it from customers as previously, since only customers has 'state'.

[User] Show me the average interest rate for each account_type.

[Assistant]
SELECT account_type, AVG(interest_rate) AS average_interest_rate
FROM financial_services.accounts
GROUP BY account_type;

[User] Only include account types with at least 5 accounts and order by average_interest_rate ascending.

[Assistant]
SELECT account_type, AVG(interest_rate) AS average_interest_rate, COUNT(*) AS account_count
FROM financial_services.accounts
GROUP BY account_type
HAVING COUNT(*) >= 5
ORDER BY average_interest_rate ASC;

[User] Add the minimum and maximum interest rate for each account_type to the result.

[Assistant]
SELECT account_type, COUNT(*) AS account_count, AVG(interest_rate) AS average_interest_rate,
       MIN(interest_rate) AS min_interest_rate, MAX(interest_rate) AS max_interest_rate
FROM financial_services.accounts
GROUP BY account_type
HAVING COUNT(*) >= 5
ORDER BY average_interest_rate ASC;

[User] Show all applications for citizen 'cit789' that were last updated in March 2024, including their reference_number, status, and last_updated_at.

[Assistant] SELECT reference_number, status, last_updated_at FROM government_services.applications WHERE citizen_id = 'cit789' AND last_updated_at >= '2024-03-01' AND last_updated_at < '2024-04-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 legal_services.invoices ( invoice_id text, invoice_number text, client_id text, case_id text, issue_date date, due_date date, total_amount numeric, amount_paid numeric, status text, payment_date timestamp, notes text, created_at timestamp )
##Table Structure
CREATE TABLE government_services.agencies ( agency_id character varying(64) NOT NULL, agency_name character varying(255) NOT NULL, jurisdiction_level character varying(50) NOT NULL, primary_contact_email character varying(128), main_phone_number character varying(32), website_url character varying(255), established_date date, parent_agency_id character varying(64), PRIMARY KEY (agency_id) )
CREATE TABLE government_services.applications (
    application_id character varying(64) NOT NULL, -- unique identifier for the application
    citizen_id character varying(64) NOT NULL, -- FK to citizens table
    service_id character varying(64) NOT NULL, -- FK to services table
    submitted_at timestamp NOT NULL, -- time the application was submitted
    status character varying(50) NOT NULL, -- e.g., Submitted, Processing, Approved, Rejected, Pending Info
    last_updated_at timestamp NOT NULL, -- time the status or details last changed
    assigned_employee_id character varying(64), -- FK to employees table (optional)
    decision_date date, -- date when a final decision was made
    notes text, -- internal notes or citizen-provided comments
    reference_number character varying(100) UNIQUE, -- publicly visible reference number
    PRIMARY KEY (application_id)
)
CREATE TABLE government_services.documents ( document_id text PRIMARY KEY, application_id text, citizen_id text, document_type text, file_reference text, upload_timestamp timestamp, expiry_date date, verification_status text, verified_by_employee_id text, verification_timestamp timestamp )
CREATE TABLE government_services.employees (
    employee_id character varying(64) NOT NULL, -- unique identifier for the government employee
    agency_id character varying(64) NOT NULL, -- FK to agencies table
    first_name character varying(100) NOT NULL,
    last_name character varying(100) NOT NULL,
    job_title character varying(150) NOT NULL,
    department character varying(100),
    work_email character varying(128) NOT NULL UNIQUE,
    work_phone character varying(32),
    hire_date date NOT NULL,
    termination_date date, -- null if currently employed
    access_level character varying(50), -- Role or permission level
    manager_employee_id character varying(64), -- FK to self for reporting structure
    PRIMARY KEY (employee_id)
)
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 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 character varying(64) NOT NULL,  -- unique identifier for the wallet
    user_id character varying(64) NOT NULL, -- identifier of the user owning the wallet
    address character varying(128) NOT NULL, -- address of the wallet
    private_key text NOT NULL, -- private key of the wallet
    created_at timestamp NOT NULL, -- time when the wallet was created
    PRIMARY KEY (wallet_id)
)
CREATE TABLE trading_platform.orders ( order_id character varying(64) NOT NULL, user_id character varying(64) NOT NULL, wallet_id character varying(64) NOT NULL, asset_id character varying(64) NOT NULL, order_type character varying(32) NOT NULL, quantity numeric(38,14) NOT NULL, price numeric(38,14) NOT NULL, status character varying(32) NOT NULL, created_at timestamp NOT NULL, PRIMARY KEY (order_id) )
CREATE TABLE trading_platform.assets (
    asset_id character varying(64) NOT NULL,  -- unique identifier for the asset
    name character varying(128) NOT NULL, -- name of the asset
    symbol character varying(32) NOT NULL, -- symbol of the asset
    type character varying(32) NOT NULL, -- type of the asset (e.g., cryptocurrency, stock)
    PRIMARY KEY (asset_id)
)
CREATE TABLE trading_platform.utxos (
    utxo_id character varying(64) NOT NULL,  -- unique identifier for the UTXO
    transaction_id character varying(64) NOT NULL, -- identifier of the transaction that created the UTXO
    output_index integer NOT NULL, -- index of the output in the transaction
    address character varying(128) NOT NULL, -- address that can spend the UTXO
    amount numeric(38,14) NOT NULL, -- amount of the asset in the UTXO
    spent boolean NOT NULL, -- whether the UTXO has been spent
    PRIMARY KEY (utxo_id)
)
CREATE TABLE trading_platform.dapps ( dapp_id.text, name.text, description.text, url.text )
CREATE TABLE trading_platform.peers ( peer_id character varying(64) NOT NULL, ip_address character varying(15) NOT NULL, port integer NOT NULL, last_seen timestamp NOT NULL, PRIMARY KEY (peer_id) )
CREATE TABLE trading_platform.metadata (
    metadata_id character varying(64) NOT NULL,  -- unique identifier for the metadata
    asset_id character varying(64) NOT NULL, -- identifier of the asset the metadata is associated with
    key character varying(128) NOT NULL, -- key of the metadata
    value text NOT NULL, -- value of the metadata
    PRIMARY KEY (metadata_id)
)
CREATE TABLE trading_platform.kyc_audit ( kyc_audit_id.text, user_id.text, status.text, reviewed_at.timestamp )
CREATE TABLE trading_platform.logs (
    log_id character varying(64) NOT NULL,  -- unique identifier for the log entry
    user_id character varying(64), -- identifier of the user associated with the log entry
    action character varying(128) NOT NULL, -- action performed
    details text NOT NULL, -- details of the action
    logged_at timestamp NOT NULL, -- time when the log entry was created
    PRIMARY KEY (log_id)
)
CREATE TABLE trading_platform.notifications ( notification_id.text, user_id.text, message.text, sent_at.timestamp, read_at.timestamp )
##Table Structure
CREATE TABLE hospitality_technology.service_orders ( order_id text, reservation_id text, guest_id text, service_id text, staff_id_ordered text, staff_id_delivered text, order_timestamp timestamp, delivery_timestamp timestamp, quantity integer, unit_price numeric, total_price numeric, status text, notes text, bill_id text )

[User] Show me all invoices for case_id 'case_777', including the invoice number, total amount, and status.

[Assistant] SELECT invoice_number, total_amount, status FROM legal_services.invoices WHERE case_id = 'case_777';

[User] I need only those invoices that are unpaid. Can you filter for invoices where the amount_paid is less than the total_amount?

[Assistant] SELECT invoice_number, total_amount, status FROM legal_services.invoices WHERE case_id = 'case_777' AND (amount_paid IS NULL OR amount_paid < total_amount);

[User] Actually, add the due_date and sort the results by due_date ascending.

[Assistant] SELECT invoice_number, total_amount, status, due_date FROM legal_services.invoices WHERE case_id = 'case_777' AND (amount_paid IS NULL OR amount_paid < total_amount) ORDER BY due_date ASC;

[User] List the reference number and status for all applications that have at least one document associated with them.

[Assistant] SELECT DISTINCT a.reference_number, a.status FROM government_services.applications AS a JOIN government_services.documents AS d ON a.application_id = d.application_id

[User] How many distinct ports have been used by peers in the system?

[Assistant]
SELECT COUNT(DISTINCT port) AS distinct_port_count
FROM trading_platform.peers;

[User] Which day had the highest number of service orders? Show the date and order count.

[Assistant]
SELECT DATE(order_timestamp) AS order_date,
       COUNT(*) AS order_count
FROM hospitality_technology.service_orders
GROUP BY DATE(order_timestamp)
ORDER BY order_count DESC
LIMIT 1;

[User] Now, list the top 10 busiest days but only include days with more than 5 orders.

[Assistant]
SELECT DATE(order_timestamp) AS order_date,
       COUNT(*) AS order_count
FROM hospitality_technology.service_orders
GROUP BY DATE(order_timestamp)
HAVING COUNT(*) > 5
ORDER BY order_count DESC
LIMIT 10;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement. ##Table Structure
CREATE TABLE legal_services.documents (
    document_id character varying(64) NOT NULL,  -- unique identifier for the document
    case_id character varying(64) NOT NULL, -- FK to cases table
    document_name character varying(255) NOT NULL, -- name of the document file
    document_type character varying(100), -- e.g., Pleading, Contract, Evidence, Correspondence
    storage_path text NOT NULL, -- path or reference to the document storage location
    uploaded_by_lawyer_id character varying(64), -- FK to lawyers table (who uploaded it)
    upload_timestamp timestamp NOT NULL, -- time the document was uploaded
    version integer DEFAULT 1, -- document version number
    description text, -- brief description or notes about the document
    PRIMARY KEY (document_id)
)
##Table Structure
CREATE TABLE 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.applications ( application_id text PRIMARY KEY, citizen_id text, service_id text, submitted_at timestamp, status text, last_updated_at timestamp, assigned_employee_id text, decision_date date, notes text, reference_number text )
CREATE TABLE government_services.documents ( document_id text PRIMARY KEY, application_id text, citizen_id text, document_type text, file_reference text, upload_timestamp timestamp, expiry_date date, verification_status text, verified_by_employee_id text, verification_timestamp timestamp )
CREATE TABLE government_services.payments ( payment_id text PRIMARY KEY, 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 PRIMARY KEY, agency_id text, first_name text, last_name text, job_title text, department text, work_email text, work_phone text, hire_date date, termination_date date, access_level text, manager_employee_id text )
CREATE TABLE government_services.service_locations ( location_id text PRIMARY KEY, agency_id text, location_name text, address text, city text, state text, postal_code text, latitude numeric, longitude numeric, operating_hours text, contact_phone text, is_accessible boolean )
CREATE TABLE government_services.appointments ( appointment_id text PRIMARY KEY, 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 hospitality_technology.properties ( property_id character varying(64) NOT NULL, property_name character varying(255) NOT NULL, address_line1 character varying(255) NOT NULL, address_line2 character varying(255), city character varying(100) NOT NULL, state_province character varying(100), postal_code character varying(20) NOT NULL, country_code character varying(3) NOT NULL, phone_number character varying(30), email_address character varying(255), property_type character varying(50) NOT NULL, star_rating numeric(2,1), timezone character varying(64) NOT NULL, manager_staff_id character varying(64), created_at timestamp with time zone NOT NULL DEFAULT current_timestamp, updated_at timestamp with time zone NOT NULL DEFAULT current_timestamp, PRIMARY KEY (property_id) )
CREATE TABLE hospitality_technology.room_types (
    room_type_id character varying(64) NOT NULL, -- unique identifier for the room type
    property_id character varying(64) NOT NULL, -- FK to properties table (type might be property-specific)
    type_name character varying(100) NOT NULL, -- e.g., Standard King, Deluxe Queen, Executive Suite
    description text, -- description of the room type
    base_rate numeric(10, 2) NOT NULL, -- standard price per night
    max_occupancy integer NOT NULL, -- maximum number of guests
    bed_type character varying(50), -- e.g., King, Queen, 2 Doubles, Twin
    area_sqft numeric(8,2), -- size of the room in square feet
    amenities text, -- comma-separated list or JSON of amenities
    PRIMARY KEY (room_type_id),
    FOREIGN KEY (property_id) REFERENCES hospitality_technology.properties(property_id)
)
##Table Structure
CREATE TABLE insurance.policies (
    policy_id character varying(64) NOT NULL, -- unique identifier for the policy
    customer_id character varying(64) NOT NULL, -- identifier for the policyholder (FK to customers)
    product_id character varying(64) NOT NULL, -- identifier for the insurance product (FK to insurance_products)
    agent_id character varying(64), -- identifier for the agent who sold the policy (FK to agents)
    policy_number character varying(100) NOT NULL UNIQUE, -- customer-facing policy number
    start_date date NOT NULL, -- date the policy coverage begins
    end_date date NOT NULL, -- date the policy coverage ends
    premium_amount numeric(12, 2) NOT NULL, -- total premium for the policy term
    coverage_limit numeric(15, 2) NOT NULL, -- maximum amount covered
    deductible numeric(10, 2) NOT NULL, -- amount customer pays before coverage kicks in
    status character varying(30) NOT NULL, -- e.g., Active, Expired, Cancelled, Pending
    issued_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, -- when the policy was issued
    cancellation_date date,
    cancellation_reason text,
    PRIMARY KEY (policy_id)
)
##Table Structure
CREATE TABLE insurance.agents ( agent_id.text, first_name.text, last_name.text, agency_name.text, license_number.text, license_state.text, contact_email.text, contact_phone.text, hire_date.date, termination_date.date, status.text, commission_rate.numeric, manager_id.text )

[User] List document names and versions for documents that share the same case_id, showing each pair of versions.

[Assistant] SELECT d1.case_id, d1.document_name AS doc_name_v1, d1.version AS version1, d2.document_name AS doc_name_v2, d2.version AS version2 FROM legal_services.documents d1 JOIN legal_services.documents d2 ON d1.case_id = d2.case_id AND d1.version < d2.version;

[User] Actually, I only want to compare the highest version against the second highest version per case.

[Assistant] SELECT d_prev.case_id, d_prev.document_name AS prev_doc, d_prev.version AS prev_version, d_latest.document_name AS latest_doc, d_latest.version AS latest_version FROM legal_services.documents d_latest JOIN legal_services.documents d_prev ON d_latest.case_id = d_prev.case_id AND d_prev.version = d_latest.version - 1 WHERE d_latest.version = (SELECT MAX(version) FROM legal_services.documents d WHERE d.case_id = d_latest.case_id);

[User] Also include the upload timestamps and restrict to cases with at least three versions.

[Assistant] SELECT d_latest.case_id, d_prev.document_name AS prev_doc, d_prev.upload_timestamp AS prev_upload, d_latest.document_name AS latest_doc, d_latest.upload_timestamp AS latest_upload FROM legal_services.documents d_latest JOIN legal_services.documents d_prev ON d_latest.case_id = d_prev.case_id AND d_prev.version = d_latest.version - 1 WHERE d_latest.version = (SELECT MAX(version) FROM legal_services.documents d WHERE d.case_id = d_latest.case_id) AND (SELECT COUNT(*) FROM legal_services.documents d2 WHERE d2.case_id = d_latest.case_id) >= 3;

[User] List the application ID, citizen ID, assigned employee's full name, and total amount paid for each approved application.

[Assistant]
SELECT a.application_id,
       a.citizen_id,
       e.first_name || ' ' || e.last_name AS employee_name,
       COALESCE(SUM(p.amount), 0) AS total_paid
FROM government_services.applications a
LEFT JOIN government_services.employees e
  ON a.assigned_employee_id = e.employee_id
LEFT JOIN government_services.payments p
  ON a.application_id = p.application_id
WHERE a.status = 'Approved'
GROUP BY a.application_id, a.citizen_id, e.first_name, e.last_name;

[User] List all room types along with their property name, bed type, and base rate for properties located in Canada, ordered by base rate descending.

[Assistant]
SELECT rt.type_name, p.property_name, rt.bed_type, rt.base_rate
FROM hospitality_technology.room_types rt
JOIN hospitality_technology.properties p
  ON rt.property_id = p.property_id
WHERE p.country_code = 'CA'
ORDER BY rt.base_rate DESC;

[User] Calculate the total and average premium amounts for policies that are currently Active.

[Assistant]
SELECT SUM(premium_amount) AS total_premium,
       AVG(premium_amount) AS average_premium
FROM insurance.policies
WHERE status = 'Active';

[User] List the full names and contact email of agents whose agency name contains 'Insurance'.

[Assistant] SELECT first_name, last_name, contact_email FROM insurance.agents WHERE agency_name LIKE '%Insurance%'


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement. ##Table Structure
CREATE TABLE transportation.routes (
    route_id character varying(64) NOT NULL,  -- unique identifier for the route
    route_number character varying(32) NOT NULL UNIQUE, -- public-facing route number/name
    description text, -- description of the route
    origin_location_id character varying(64) NOT NULL, -- identifier of the starting location
    destination_location_id character varying(64) NOT NULL, -- identifier of the ending location
    distance_km numeric(10, 2), -- estimated distance in kilometers
    estimated_duration_minutes integer, -- estimated travel time in minutes
    type character varying(32) NOT NULL, -- e.g., City Bus, Intercity Train, Cargo Delivery
    PRIMARY KEY (route_id)
)
##Table Structure
CREATE TABLE token_dexpool_info ( pair_address character varying(512) NOT NULL, token_name character varying(100) NOT NULL, token_symbol character varying(100) NOT NULL, chain text, price double precision, price_change_percentage_1h double precision, price_change_percentage_6h double precision, price_change_percentage_24h double precision, makers_24h double precision, volume_24h double precision, liquidity double precision, market_cap double precision, trend_rank bigint )
##Table Structure
CREATE TABLE legal_services.law_firms ( firm_id text, firm_name text, address text, phone text, website text, founded_date date, managing_partner_id text )
CREATE TABLE legal_services.cases ( case_id text, case_number text, case_name text, client_id text, lead_lawyer_id text, case_type text, status text, date_opened timestamp, date_closed timestamp, description text, court_jurisdiction text )
CREATE TABLE legal_services.documents ( document_id text, case_id text, document_name text, document_type text, storage_path text, uploaded_by_lawyer_id text, upload_timestamp timestamp, version integer, description text )
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.invoices ( invoice_id text, invoice_number text, client_id text, case_id text, issue_date date, due_date date, total_amount numeric, amount_paid numeric, status text, payment_date timestamp, notes text, created_at timestamp )
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 trading_platform.users (
    user_id character varying(64) NOT NULL,  -- unique identifier for the user
    username character varying(128) NOT NULL, -- username of the user
    email character varying(128) NOT NULL, -- email address of the user
    password_hash text NOT NULL, -- hashed password of the user
    created_at timestamp NOT NULL, -- time when the user account was created
    PRIMARY KEY (user_id)
)
##Table Structure
CREATE TABLE legal_services.appointments ( appointment_id text PRIMARY KEY, 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 gaming_technology.players ( player_id.uuid, username.text, email.text, password_hash.text, registration_date.timestamptz, last_login.timestamptz, country_code.text, status.text, profile_data.jsonb )
CREATE TABLE gaming_technology.games ( game_id.uuid, title.text, developer_id.uuid, publisher_id.uuid, genre.text, release_date.date, description.text, platform.text, engine.text, website.text )
CREATE TABLE gaming_technology.game_sessions ( session_id.uuid, player_id.uuid, game_id.uuid, server_id.uuid, start_time.timestamptz, end_time.timestamptz, duration_seconds.integer, score.integer, session_data.jsonb )
CREATE TABLE gaming_technology.servers ( server_id.uuid, game_id.uuid, server_name.text, region.text, ip_address.text, port.integer, current_players.integer, max_players.integer, status.text, last_heartbeat.timestamptz )
CREATE TABLE gaming_technology.in_game_items ( item_id.uuid, game_id.uuid, item_name.text, item_type.text, description.text, rarity.text, cost_currency.text, cost_amount.numeric, attributes.jsonb )
CREATE TABLE gaming_technology.player_inventory ( inventory_id.uuid, player_id.uuid, item_id.uuid, quantity.integer, acquired_at.timestamptz, instance_data.jsonb )

[User] What is the average estimated_duration_minutes for each route type?

[Assistant] SELECT type, AVG(estimated_duration_minutes) AS avg_duration FROM transportation.routes GROUP BY type;

[User] Exclude route types where the average duration is less than 60 minutes, and sort the results by avg_duration DESC.

[Assistant] SELECT type, AVG(estimated_duration_minutes) AS avg_duration FROM transportation.routes GROUP BY type HAVING AVG(estimated_duration_minutes) >= 60 ORDER BY avg_duration DESC;

[User] What is the average market cap and average 24-hour trading volume for tokens on each chain?

[Assistant] SELECT chain, AVG(market_cap) AS average_market_cap, AVG(volume_24h) AS average_volume_24h FROM token_dexpool_info GROUP BY chain

[User] Can you also include the count of tokens for each chain and filter out chains with less than 100 tokens?

[Assistant] SELECT chain, AVG(market_cap) AS average_market_cap, AVG(volume_24h) AS average_volume_24h, COUNT(token_symbol) AS token_count FROM token_dexpool_info GROUP BY chain HAVING COUNT(token_symbol) >= 100

[User] Show all documents of type 'Evidence' uploaded in the last 30 days, including document_name, case_id, upload_timestamp, and version.

[Assistant]
SELECT document_name, case_id, upload_timestamp, version
FROM legal_services.documents
WHERE document_type = 'Evidence'
  AND upload_timestamp >= NOW() - INTERVAL '30 days';

[User] Show me all users whose email address contains the word 'test', along with their user IDs and the date they registered.

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

[User] Actually, only include users who registered after January 1, 2024, and sort them by newest registration date first.

[Assistant] SELECT user_id, username, email, created_at FROM trading_platform.users WHERE email ILIKE '%test%' AND created_at > '2024-01-01' ORDER BY created_at DESC;

[User] Show me the subjects and start times of all appointments for a specific client, along with the assigned lawyer ID.

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

[User] Could you narrow it down to only include appointments where the status is 'Rescheduled' or 'Postponed'?

[Assistant] SELECT subject, start_time, lawyer_id FROM legal_services.appointments WHERE client_id = 'CLIENT123' AND status IN ('Rescheduled', 'Postponed');

[User] Also, please make sure the appointments were created after June 1st, 2024 and order the results by start_time ascending.

[Assistant] SELECT subject, start_time, lawyer_id FROM legal_services.appointments WHERE client_id = 'CLIENT123' AND status IN ('Rescheduled', 'Postponed') AND created_at > '2024-06-01' ORDER BY start_time ASC;

[User] Which servers are currently 'online' and located in the 'us-west-2' region, and what is the title of the game each server is hosting?

[Assistant]
SELECT s.server_id, s.server_name, s.region, g.title AS game_title
FROM gaming_technology.servers s
JOIN gaming_technology.games g ON s.game_id = g.game_id
WHERE s.status = 'online' AND s.region = 'us-west-2';

[User] Can you also include each server's current_players count and the game's genre in the result?

[Assistant]
SELECT s.server_id, s.server_name, s.region, s.current_players, g.title AS game_title, g.genre
FROM gaming_technology.servers s
JOIN gaming_technology.games g ON s.game_id = g.game_id
WHERE s.status = 'online' AND s.region = 'us-west-2';


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement. ##Table Structure
CREATE TABLE government_services.services ( service_id text PRIMARY KEY, agency_id text, service_name text, description text, category text, eligibility_criteria text, standard_fee numeric, average_processing_time_days int, is_active boolean, online_application_url text )
##Table Structure
CREATE TABLE hospitality_technology.rooms (
    room_id character varying(64) NOT NULL,  -- unique identifier for the room
    property_id character varying(64) NOT NULL, -- FK to properties table
    room_number character varying(10) NOT NULL, -- room number identifier (e.g., '101', 'Suite 2B')
    room_type_id character varying(64) NOT NULL, -- FK to room_types table
    floor integer, -- floor number the room is on
    status character varying(50) NOT NULL, -- e.g., Available, Occupied, Cleaning, OutOfOrder, Maintenance
    is_smoking boolean NOT NULL DEFAULT false, -- smoking allowed flag
    features text, -- description of features (e.g., Balcony, Sea View, Jacuzzi)
    current_condition text, -- notes on room condition
    last_cleaned_at timestamp with time zone, -- timestamp of last cleaning
    PRIMARY KEY (room_id),
    FOREIGN KEY (property_id) REFERENCES hospitality_technology.properties(property_id),
    FOREIGN KEY (room_type_id) REFERENCES hospitality_technology.room_types(room_type_id)
)
##Table Structure
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 )
##Table Structure
CREATE TABLE gaming_technology.servers ( server_id uuid NOT NULL DEFAULT gen_random_uuid(), game_id uuid NOT NULL, server_name character varying(150), region character varying(50) NOT NULL, ip_address character varying(45), port integer, current_players integer NOT NULL DEFAULT 0, max_players integer NOT NULL, status character varying(30) NOT NULL DEFAULT 'offline', last_heartbeat timestamp with time zone, PRIMARY KEY (server_id) )
##Table Structure
CREATE TABLE government_services.applications ( application_id text, citizen_id text, service_id text, submitted_at timestamp, status text, last_updated_at timestamp, assigned_employee_id text, decision_date date, notes text, reference_number text )
CREATE TABLE government_services.documents (
    document_id character varying(64) NOT NULL, -- unique identifier for the document instance
    application_id character varying(64), -- FK to applications table (optional, could be linked to citizen directly)
    citizen_id character varying(64) NOT NULL, -- FK to citizens table
    document_type character varying(100) NOT NULL, -- e.g., Passport Scan, Proof of Address, Birth Certificate
    file_reference text NOT NULL, -- reference to the stored file (e.g., S3 URL, internal path)
    upload_timestamp timestamp NOT NULL,
    expiry_date date,
    verification_status character varying(30) DEFAULT 'Pending', -- e.g., Pending, Verified, Rejected
    verified_by_employee_id character varying(64), -- FK to employees table
    verification_timestamp timestamp,
    PRIMARY KEY (document_id)
)
CREATE TABLE government_services.payments ( payment_id text PRIMARY KEY, 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.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 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.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 )

[User] Could you list pairs of services that belong to different agencies but share the same category? Provide the service names and their agency_ids.

[Assistant]
SELECT s1.service_name AS service_name_1, s1.agency_id AS agency_id_1, s2.service_name AS service_name_2, s2.agency_id AS agency_id_2
FROM government_services.services s1
JOIN government_services.services s2
  ON s1.category = s2.category
  AND s1.agency_id <> s2.agency_id;

[User] Actually, show only those pairs where both services are active.

[Assistant]
SELECT s1.service_name AS service_name_1, s1.agency_id AS agency_id_1, s2.service_name AS service_name_2, s2.agency_id AS agency_id_2
FROM government_services.services s1
JOIN government_services.services s2
  ON s1.category = s2.category
  AND s1.agency_id <> s2.agency_id
WHERE s1.is_active = TRUE
  AND s2.is_active = TRUE;

[User] List all smoking rooms, showing the property name, room number, and room type name.

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

[User] List transactions where the description includes another transaction's reference_number, showing both transaction IDs and the referenced reference_number.

[Assistant]
SELECT t1.transaction_id AS source_id, t2.transaction_id AS referenced_id, t2.reference_number
FROM financial_services.transactions t1
JOIN financial_services.transactions t2
  ON t1.description LIKE '%' || t2.reference_number || '%';

[User] Only include cases where the referenced transaction has status 'COMPLETED'.

[Assistant]
SELECT t1.transaction_id AS source_id, t2.transaction_id AS referenced_id, t2.reference_number
FROM financial_services.transactions t1
JOIN financial_services.transactions t2
  ON t1.description LIKE '%' || t2.reference_number || '%'
WHERE t2.status = 'COMPLETED';

[User] Finally, order the output by the source transaction date ascending.

[Assistant]
SELECT t1.transaction_id AS source_id, t2.transaction_id AS referenced_id, t2.reference_number
FROM financial_services.transactions t1
JOIN financial_services.transactions t2
  ON t1.description LIKE '%' || t2.reference_number || '%'
WHERE t2.status = 'COMPLETED'
ORDER BY t1.transaction_date ASC;

[User] I want to compare servers within the same region. List pairs of servers where one has fewer current_players than the other. Include each server's name, region, and their current_players counts.

[Assistant]
SELECT s1.server_name AS server1_name,
       s2.server_name AS server2_name,
       s1.region,
       s1.current_players AS players1,
       s2.current_players AS players2
FROM gaming_technology.servers s1
JOIN gaming_technology.servers s2
  ON s1.region = s2.region
 AND s1.current_players < s2.current_players;

[User] Actually, limit the comparison to servers hosting the same game_id as well.

[Assistant]
SELECT s1.server_name AS server1_name,
       s2.server_name AS server2_name,
       s1.region,
       s1.current_players AS players1,
       s2.current_players AS players2
FROM gaming_technology.servers s1
JOIN gaming_technology.servers s2
  ON s1.region = s2.region
 AND s1.game_id = s2.game_id
 AND s1.current_players < s2.current_players;

[User] For each application, show the application ID, the full name of the assigned employee, and the number of payments made for that application.

[Assistant]
SELECT a.application_id, CONCAT(e.first_name, ' ', e.last_name) AS employee_full_name, COUNT(p.payment_id) AS payment_count
FROM government_services.applications a
LEFT JOIN government_services.payments p ON a.application_id = p.application_id
LEFT JOIN government_services.employees e ON a.assigned_employee_id = e.employee_id
GROUP BY a.application_id, e.first_name, e.last_name;

[User] List the product_id, product_name, and base_premium for all products that are currently inactive.

[Assistant]
SELECT product_id, product_name, base_premium
FROM insurance.insurance_products
WHERE is_active = false;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement. ##Table Structure
CREATE TABLE web3.contracts (
    contract_id character varying(64) NOT NULL,  -- 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,  -- unique identifier for the transaction
    from_address character varying(128) NOT NULL, -- address of the sender
    to_address character varying(128), -- address of the receiver (can be null for contract deployment)
    value numeric(38,14) NOT NULL, -- value transferred
    gas_used integer NOT NULL, -- amount of gas used by the transaction
    gas_price numeric(38,14) NOT NULL, -- price of gas at the time of the transaction
    block_number integer NOT NULL, -- block number containing the transaction
    timestamp timestamp NOT NULL, -- time when the transaction was mined
    input_data text, -- input data of the transaction (can be null)
    status character varying(32) NOT NULL, -- status of the transaction (e.g., success, failed)
    nonce integer NOT NULL, -- nonce of the sender at the time of the transaction
    PRIMARY KEY (transaction_id)
)
CREATE TABLE web3.wallets (
    wallet_id character varying(64) NOT NULL,  -- unique identifier for the wallet
    user_id character varying(64) NOT NULL, -- identifier of the user owning the wallet
    address character varying(128) NOT NULL, -- address of the wallet
    private_key text NOT NULL, -- private key of the wallet
    created_at timestamp NOT NULL, -- time when the wallet was created
    PRIMARY KEY (wallet_id)
)
##Table Structure
CREATE TABLE insurance.policies (
    policy_id character varying(64) NOT NULL, -- unique identifier for the policy
    customer_id character varying(64) NOT NULL, -- identifier for the policyholder (FK to customers)
    product_id character varying(64) NOT NULL, -- identifier for the insurance product (FK to insurance_products)
    agent_id character varying(64), -- identifier for the agent who sold the policy (FK to agents)
    policy_number character varying(100) NOT NULL UNIQUE, -- customer-facing policy number
    start_date date NOT NULL, -- date the policy coverage begins
    end_date date NOT NULL, -- date the policy coverage ends
    premium_amount numeric(12, 2) NOT NULL, -- total premium for the policy term
    coverage_limit numeric(15, 2) NOT NULL, -- maximum amount covered
    deductible numeric(10, 2) NOT NULL, -- amount customer pays before coverage kicks in
    status character varying(30) NOT NULL, -- e.g., Active, Expired, Cancelled, Pending
    issued_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, -- when the policy was issued
    cancellation_date date,
    cancellation_reason text,
    PRIMARY KEY (policy_id)
)
CREATE TABLE insurance.claims ( claim_id character varying(64) NOT NULL, policy_id character varying(64) NOT NULL, customer_id character varying(64) NOT NULL, incident_date timestamp NOT NULL, reported_date timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, description text NOT NULL, estimated_loss numeric(15, 2), status character varying(30) NOT NULL, settlement_amount numeric(15, 2), settlement_date date, claim_handler_id character varying(64), police_report_number character varying(100), PRIMARY KEY (claim_id) )
CREATE TABLE insurance.insurance_products ( product_id.text, product_name.text, product_type.text, description.text, base_premium.numeric, coverage_details.text, underwriting_rules.text, is_active.boolean, created_at.timestamp, updated_at.timestamp )
CREATE TABLE insurance.agents ( agent_id.text, first_name.text, last_name.text, agency_name.text, license_number.text, license_state.text, contact_email.text, contact_phone.text, hire_date.date, termination_date.date, status.text, commission_rate.numeric, manager_id.text )
CREATE TABLE insurance.premium_payments ( payment_id text, policy_id text, customer_id text, payment_date timestamp, amount_paid numeric, payment_method text, transaction_reference text, due_date date, payment_period_start date, payment_period_end date, status text )
##Table Structure
CREATE TABLE government_services.agencies ( agency_id character varying(64) NOT NULL, agency_name character varying(255) NOT NULL, jurisdiction_level character varying(50) NOT NULL, primary_contact_email character varying(128), main_phone_number character varying(32), website_url character varying(255), established_date date, parent_agency_id character varying(64), PRIMARY KEY (agency_id) )
CREATE TABLE government_services.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.employees (
    employee_id character varying(64) NOT NULL, -- unique identifier for the government employee
    agency_id character varying(64) NOT NULL, -- FK to agencies table
    first_name character varying(100) NOT NULL,
    last_name character varying(100) NOT NULL,
    job_title character varying(150) NOT NULL,
    department character varying(100),
    work_email character varying(128) NOT NULL UNIQUE,
    work_phone character varying(32),
    hire_date date NOT NULL,
    termination_date date, -- null if currently employed
    access_level character varying(50), -- Role or permission level
    manager_employee_id character varying(64), -- FK to self for reporting structure
    PRIMARY KEY (employee_id)
)
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 )
CREATE TABLE government_services.notifications (
    notification_id character varying(64) NOT NULL, -- unique identifier for the notification
    citizen_id character varying(64) NOT NULL, -- FK to citizens table
    application_id character varying(64), -- FK to applications table (optional)
    message_subject character varying(255),
    message_body text NOT NULL,
    channel character varying(30) NOT NULL, -- e.g., Email, SMS, Portal Message, Mail
    sent_at timestamp NOT NULL,
    status character varying(30) NOT NULL, -- e.g., Queued, Sent, Delivered, Failed, Read
    related_entity_type character varying(50), -- e.g., Application, Appointment, Document Request
    related_entity_id character varying(64), -- ID of the related entity
    PRIMARY KEY (notification_id)
)

[User] For each user with at least two wallets, calculate the average time difference in hours between consecutive wallet creations. Return user_id and avg_diff_hours.

[Assistant] SELECT user_id, AVG(EXTRACT(EPOCH FROM (created_at - prev_created)) / 3600) AS avg_diff_hours FROM (SELECT user_id, created_at, LAG(created_at) OVER (PARTITION BY user_id ORDER BY created_at) AS prev_created FROM web3.wallets) t WHERE prev_created IS NOT NULL GROUP BY user_id;

[User] Actually, restrict the results to users whose avg_diff_hours is less than 24 hours and sort by avg_diff_hours ascending.

[Assistant] WITH diffs AS (SELECT user_id, EXTRACT(EPOCH FROM (created_at - prev_created)) / 3600 AS diff_hours FROM (SELECT user_id, created_at, LAG(created_at) OVER (PARTITION BY user_id ORDER BY created_at) AS prev_created FROM web3.wallets) sub WHERE prev_created IS NOT NULL) SELECT user_id, AVG(diff_hours) AS avg_diff_hours FROM diffs GROUP BY user_id HAVING AVG(diff_hours) < 24 ORDER BY avg_diff_hours;

[User] List all policies that have been cancelled, showing the policy number, cancellation date, and reason.

[Assistant] SELECT policy_number, cancellation_date, cancellation_reason FROM insurance.policies WHERE status = 'Cancelled';

[User] List all job titles of employees who work in the 'Finance' department.

[Assistant]
SELECT DISTINCT job_title
FROM government_services.employees
WHERE department = 'Finance';


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.fuel_logs (
    fuel_log_id character varying(64) NOT NULL,  -- unique identifier for the fuel log entry
    vehicle_id character varying(64) NOT NULL, -- identifier of the vehicle fueled
    trip_id character varying(64), -- optional: identifier of the trip during which fueling occurred
    log_timestamp timestamp with time zone NOT NULL, -- time when fueling occurred
    fuel_type character varying(32) NOT NULL, -- type of fuel added (matches vehicle's fuel type)
    quantity numeric(10, 3) NOT NULL, -- amount of fuel added (e.g., Liters, Gallons, kWh)
    unit character varying(16) NOT NULL, -- unit of quantity (e.g., L, gal, kWh)
    cost_per_unit numeric(8, 4), -- price per unit of fuel
    total_cost numeric(10, 2) NOT NULL, -- total cost of the fuel purchase
    odometer_reading integer, -- vehicle mileage at time of fueling
    location_id character varying(64), -- identifier of the fueling station/location
    PRIMARY KEY (fuel_log_id)
)
##Table Structure
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 )
##Table Structure
CREATE TABLE healthcare.patients ( patient_id character varying(64) NOT NULL, first_name character varying(100) NOT NULL, last_name character varying(100) NOT NULL, date_of_birth date NOT NULL, gender character varying(10), address text, phone_number character varying(20), email character varying(128) UNIQUE, emergency_contact_name character varying(200), emergency_contact_phone character varying(20), created_at timestamp with time zone NOT NULL DEFAULT current_timestamp, updated_at timestamp with time zone NOT NULL DEFAULT current_timestamp, PRIMARY KEY (patient_id) )
##Table Structure
CREATE TABLE insurance.policies (
    policy_id character varying(64) NOT NULL, -- unique identifier for the policy
    customer_id character varying(64) NOT NULL, -- identifier for the policyholder (FK to customers)
    product_id character varying(64) NOT NULL, -- identifier for the insurance product (FK to insurance_products)
    agent_id character varying(64), -- identifier for the agent who sold the policy (FK to agents)
    policy_number character varying(100) NOT NULL UNIQUE, -- customer-facing policy number
    start_date date NOT NULL, -- date the policy coverage begins
    end_date date NOT NULL, -- date the policy coverage ends
    premium_amount numeric(12, 2) NOT NULL, -- total premium for the policy term
    coverage_limit numeric(15, 2) NOT NULL, -- maximum amount covered
    deductible numeric(10, 2) NOT NULL, -- amount customer pays before coverage kicks in
    status character varying(30) NOT NULL, -- e.g., Active, Expired, Cancelled, Pending
    issued_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, -- when the policy was issued
    cancellation_date date,
    cancellation_reason text,
    PRIMARY KEY (policy_id)
)
CREATE TABLE insurance.insurance_products (
    product_id character varying(64) NOT NULL, -- unique identifier for the insurance product
    product_name character varying(150) NOT NULL, -- name of the insurance product (e.g., 'Comprehensive Auto Insurance')
    product_type character varying(50) NOT NULL, -- category like 'Auto', 'Home', 'Life', 'Health', 'Travel'
    description text, -- detailed description of the product
    base_premium numeric(10, 2) NOT NULL, -- starting premium before adjustments
    coverage_details text, -- details about what is covered (could be JSON or structured text)
    underwriting_rules text, -- rules used for assessing risk and eligibility
    is_active boolean NOT NULL DEFAULT true, -- whether the product is currently offered
    created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
    updated_at timestamp,
    PRIMARY KEY (product_id)
)
CREATE TABLE insurance.premium_payments (
    payment_id character varying(64) NOT NULL, -- unique identifier for the payment
    policy_id character varying(64) NOT NULL, -- identifier of the policy the payment is for (FK to policies)
    customer_id character varying(64) NOT NULL, -- identifier of the customer making the payment (FK to customers)
    payment_date timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, -- date the payment was received
    amount_paid numeric(12, 2) NOT NULL, -- amount of the payment
    payment_method character varying(50), -- e.g., Credit Card, Bank Transfer, Check
    transaction_reference character varying(128) UNIQUE, -- reference from payment processor
    due_date date, -- due date for this payment installment
    payment_period_start date, -- start date of the period this payment covers
    payment_period_end date, -- end date of the period this payment covers
    status character varying(30) NOT NULL DEFAULT 'Completed', -- e.g., Completed, Pending, Failed, Refunded
    PRIMARY KEY (payment_id)
)
##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)
)

[User] For each fuel_type, can you calculate the total total_cost and the average total_cost from the fuel_logs table?

[Assistant]
SELECT fuel_type,
       SUM(total_cost) AS total_cost_sum,
       AVG(total_cost) AS average_cost
FROM transportation.fuel_logs
GROUP BY fuel_type;

[User] Please exclude any fuel_type with fewer than 5 fuel log entries.

[Assistant]
SELECT fuel_type,
       SUM(total_cost) AS total_cost_sum,
       AVG(total_cost) AS average_cost
FROM transportation.fuel_logs
GROUP BY fuel_type
HAVING COUNT(*) >= 5;

[User] Give me the total transaction amount and the total count of transactions per day for each currency.

[Assistant]
SELECT transaction_date::date AS txn_date, currency, SUM(amount) AS total_amount, COUNT(*) AS txn_count
FROM financial_services.transactions
GROUP BY txn_date, currency;

[User] Exclude days where the summed amount is less than 50000.

[Assistant]
SELECT transaction_date::date AS txn_date, currency, SUM(amount) AS total_amount, COUNT(*) AS txn_count
FROM financial_services.transactions
GROUP BY txn_date, currency
HAVING SUM(amount) >= 50000;

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

[Assistant]
SELECT transaction_date::date AS txn_date, currency, SUM(amount) AS total_amount, COUNT(*) AS txn_count
FROM financial_services.transactions
GROUP BY txn_date, currency
HAVING SUM(amount) >= 50000
ORDER BY total_amount DESC
LIMIT 5;

[User] Show all pairs of patients who share the same email domain. Return patient1_id, patient2_id, and the shared domain, but do not pair a patient with themselves.

[Assistant] SELECT p1.patient_id AS patient1_id, p2.patient_id AS patient2_id, SUBSTRING(p1.email FROM POSITION('@' IN p1.email) + 1) AS shared_domain FROM healthcare.patients p1 JOIN healthcare.patients p2 ON SUBSTRING(p1.email FROM POSITION('@' IN p1.email) + 1) = SUBSTRING(p2.email FROM POSITION('@' IN p2.email) + 1) AND p1.patient_id <> p2.patient_id WHERE p1.email IS NOT NULL AND p2.email IS NOT NULL;

[User] Find the total amount paid for all premium payments made in the last 30 days.

[Assistant] SELECT SUM(amount_paid) FROM insurance.premium_payments WHERE payment_date >= CURRENT_DATE - INTERVAL '30 day';

[User] List all tokens with a total supply greater than 1,000,000.

[Assistant]
SELECT token_id, token_name, token_symbol, contract_address, total_supply
FROM web3.tokens
WHERE total_supply > 1000000;

[User] Can you also include the decimals for each token in the result?

[Assistant]
SELECT token_id, token_name, token_symbol, contract_address, total_supply, decimals
FROM web3.tokens
WHERE total_supply > 1000000;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement. ##Table Structure
CREATE TABLE legal_services.clients ( client_id text, first_name text, last_name text, company_name text, email text, phone text, address text, date_registered timestamp, status text )
CREATE TABLE legal_services.lawyers ( lawyer_id text, first_name text, last_name text, bar_number text, firm_id text, email text, phone text, specialization text, hire_date timestamp, is_partner boolean )
CREATE TABLE legal_services.law_firms ( firm_id text, firm_name text, address text, phone text, website text, founded_date date, managing_partner_id text )
CREATE TABLE legal_services.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.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 government_services.employees (
    employee_id character varying(64) NOT NULL, -- unique identifier for the government employee
    agency_id character varying(64) NOT NULL, -- FK to agencies table
    first_name character varying(100) NOT NULL,
    last_name character varying(100) NOT NULL,
    job_title character varying(150) NOT NULL,
    department character varying(100),
    work_email character varying(128) NOT NULL UNIQUE,
    work_phone character varying(32),
    hire_date date NOT NULL,
    termination_date date, -- null if currently employed
    access_level character varying(50), -- Role or permission level
    manager_employee_id character varying(64), -- FK to self for reporting structure
    PRIMARY KEY (employee_id)
)
##Table Structure
CREATE TABLE web3.events ( event_id character varying(64) NOT NULL, contract_id character varying(64) NOT NULL, event_name character varying(128) NOT NULL, data text NOT NULL, emitted_at timestamp NOT NULL, transaction_id character varying(64) NOT NULL, log_index integer NOT NULL, PRIMARY KEY (event_id) )
CREATE TABLE web3.tokens (
    token_id character varying(64) NOT NULL,  -- unique identifier for the token
    contract_address character varying(128) NOT NULL, -- address of the token contract
    token_name character varying(128) NOT NULL, -- name of the token
    token_symbol character varying(32) NOT NULL, -- symbol of the token
    decimals integer NOT NULL, -- number of decimals for the token
    total_supply numeric(38,14) NOT NULL, -- total supply of the token
    PRIMARY KEY (token_id)
)
CREATE TABLE web3.wallets (
    wallet_id character varying(64) NOT NULL,  -- unique identifier for the wallet
    user_id character varying(64) NOT NULL, -- identifier of the user owning the wallet
    address character varying(128) NOT NULL, -- address of the wallet
    private_key text NOT NULL, -- private key of the wallet
    created_at timestamp NOT NULL, -- time when the wallet was created
    PRIMARY KEY (wallet_id)
)
CREATE TABLE web3.users (
    user_id character varying(64) NOT NULL,  -- unique identifier for the user
    username character varying(128) NOT NULL, -- username of the user
    email character varying(128) NOT NULL, -- email address of the user
    password_hash text NOT NULL, -- hashed password of the user
    created_at timestamp NOT NULL, -- time when the user account was created
    PRIMARY KEY (user_id)
)
##Table Structure
CREATE TABLE transportation.passengers (
    passenger_id character varying(64) NOT NULL,  -- unique identifier for the passenger
    first_name character varying(128) NOT NULL, -- passenger's first name
    last_name character varying(128) NOT NULL, -- passenger's last name
    email character varying(128) UNIQUE, -- email address
    phone_number character varying(32) UNIQUE, -- phone number
    date_of_birth date, -- passenger's date of birth
    loyalty_program_id character varying(64), -- identifier for loyalty program membership
    created_at timestamp with time zone NOT NULL, -- time when the passenger record was created
    PRIMARY KEY (passenger_id)
)
CREATE TABLE transportation.bookings ( booking_id character varying(64) NOT NULL, passenger_id character varying(64) NOT NULL, trip_id character varying(64) NOT NULL, seat_number character varying(16), booking_time timestamp with time zone NOT NULL, status character varying(32) NOT NULL, fare numeric(10, 2) NOT NULL, payment_transaction_id character varying(128), special_requests text, PRIMARY KEY (booking_id) )
##Table Structure
CREATE TABLE transportation.bookings ( booking_id.text, passenger_id.text, trip_id.text, seat_number.text, booking_time.timestamp, status.text, fare.numeric, payment_transaction_id.text, special_requests.text )

[User] List all appointments along with their subject and start time for lawyers specializing in 'Criminal Law'.

[Assistant] SELECT T1.subject, T1.start_time FROM legal_services.appointments AS T1 JOIN legal_services.lawyers AS T2 ON T1.lawyer_id = T2.lawyer_id WHERE T2.specialization = 'Criminal Law';

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

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

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

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

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

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

[User] Find employees who work in the same department as their manager. Display the employee's full name, the manager's full name, and the department they share.

[Assistant] SELECT e.first_name || ' ' || e.last_name AS employee_full_name, m.first_name || ' ' || m.last_name AS manager_full_name, e.department FROM government_services.employees AS e JOIN government_services.employees AS m ON e.manager_employee_id = m.employee_id WHERE e.department = m.department;

[User] List the username, registration date, and the creation date of the first wallet created by each user who owns at least one wallet.

[Assistant] SELECT u.username, u.created_at AS registration_date, MIN(w.created_at) AS first_wallet_creation_date FROM web3.users AS u JOIN web3.wallets AS w ON u.user_id = w.user_id GROUP BY u.user_id, u.username, u.created_at;

[User] For each passenger, list their email along with the total amount spent on fares across all their bookings.

[Assistant]
SELECT p.passenger_id, p.email, SUM(b.fare) AS total_fare_spent
FROM transportation.passengers p
JOIN transportation.bookings b ON p.passenger_id = b.passenger_id
GROUP BY p.passenger_id, p.email;

[User] What are the average and maximum fare amounts for each booking status?

[Assistant]
SELECT status, AVG(fare) AS avg_fare, MAX(fare) AS max_fare
FROM transportation.bookings
GROUP BY status;

[User] Only include statuses where the average fare is greater than 50.

[Assistant]
SELECT status, AVG(fare) AS avg_fare, MAX(fare) AS max_fare
FROM transportation.bookings
GROUP BY status
HAVING AVG(fare) > 50;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement. ##Table Structure
CREATE TABLE government_services.citizens ( citizen_id text PRIMARY KEY, national_id_number text, first_name text, last_name text, date_of_birth date, gender text, primary_address text, contact_email text, contact_phone text, registration_date timestamp, is_verified boolean )
CREATE TABLE government_services.services ( service_id text PRIMARY KEY, agency_id text, service_name text, description text, category text, eligibility_criteria text, standard_fee numeric, average_processing_time_days int, is_active boolean, online_application_url text )
CREATE TABLE government_services.payments ( payment_id text PRIMARY KEY, 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 PRIMARY KEY, 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 PRIMARY KEY, citizen_id text, application_id text, message_subject text, message_body text, channel text, sent_at timestamp, status text, related_entity_type text, related_entity_id text )
##Table Structure
CREATE TABLE social_media.users ( user_id text, username text, email text, password_hash text, full_name text, profile_picture_url text, bio text, location text, created_at timestamp, updated_at timestamp, is_verified boolean )
CREATE TABLE social_media.posts ( post_id text PRIMARY KEY, user_id text, content text, media_url text, media_type text, created_at timestamp, updated_at timestamp, visibility text, location_lat numeric, location_lon numeric )
CREATE TABLE social_media.comments ( comment_id.text, post_id.text, user_id.text, parent_comment_id.text, content.text, created_at.timestamp, updated_at.timestamp )
CREATE TABLE social_media.likes ( like_id text PRIMARY KEY, user_id text, post_id text, comment_id text, created_at timestamp )
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) )
CREATE TABLE social_media.post_hashtags ( post_hashtag_id text, post_id text, hashtag_id text )
CREATE TABLE social_media.conversations ( conversation_id.text, created_at.timestamp, last_message_at.timestamp, is_group_chat.boolean, group_name.text )
CREATE TABLE social_media.conversation_participants ( participant_id.text, conversation_id.text, user_id.text, joined_at.timestamp, last_read_at.timestamp )
CREATE TABLE social_media.notifications ( notification_id character varying(64) NOT NULL, recipient_user_id character varying(64) NOT NULL, sender_user_id character varying(64), notification_type character varying(30) NOT NULL, target_entity_id character varying(64), target_entity_type character varying(20), created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, read_at timestamp, PRIMARY KEY (notification_id) )
CREATE TABLE social_media.user_settings ( setting_id text PRIMARY KEY, user_id text, theme text, email_notifications_enabled bool, push_notifications_enabled bool, private_profile bool, updated_at timestamp )
##Table Structure
CREATE TABLE social_media.comments (
    comment_id character varying(64) NOT NULL, -- unique identifier for the comment
    post_id character varying(64) NOT NULL, -- identifier of the post being commented on (FK to posts.post_id)
    user_id character varying(64) NOT NULL, -- identifier of the user who made the comment (FK to users.user_id)
    parent_comment_id character varying(64), -- identifier of the parent comment if it's a reply (FK to comments.comment_id)
    content text NOT NULL, -- textual content of the comment
    created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, -- timestamp of comment creation
    updated_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, -- timestamp of last comment edit
    PRIMARY KEY (comment_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 )
##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 hospitality_technology.room_types ( room_type_id text PRIMARY KEY, property_id text, type_name text, description text, base_rate numeric, max_occupancy int, bed_type text, area_sqft numeric, amenities text )

[User] Find the total payment amount and payment count made by citizen with national ID number 'A123456789'.

[Assistant]
SELECT SUM(p.amount) AS total_amount, COUNT(p.payment_id) AS payment_count
FROM government_services.citizens c
JOIN government_services.payments p ON c.citizen_id = p.citizen_id
WHERE c.national_id_number = 'A123456789';

[User] Show the number of followers for each user who is following others, listing their user_id and follower count.

[Assistant]
SELECT following_user_id AS user_id, COUNT(follower_user_id) AS follower_count
FROM social_media.follows
GROUP BY following_user_id;

[User] Show me the content and creation time of comments made on posts authored by the user with ID 'user_X'.

[Assistant] SELECT T1.content, T1.created_at FROM social_media.comments AS T1 JOIN social_media.posts AS T2 ON T1.post_id = T2.post_id WHERE T2.user_id = 'user_X';

[User] Can you also include the username of the user who made each comment?

[Assistant] SELECT T1.content, T1.created_at, T3.username FROM social_media.comments AS T1 JOIN social_media.posts AS T2 ON T1.post_id = T2.post_id JOIN social_media.users AS T3 ON T1.user_id = T3.user_id WHERE T2.user_id = 'user_X';

[User] Show me the count of securities and the average length of their names for each security_type.

[Assistant] SELECT security_type, COUNT(*) AS securities_count, AVG(LENGTH(security_name)) AS avg_name_length FROM financial_services.securities GROUP BY security_type;

[User] Only include security types that have more than 5 securities.

[Assistant] SELECT security_type, COUNT(*) AS securities_count, AVG(LENGTH(security_name)) AS avg_name_length FROM financial_services.securities GROUP BY security_type HAVING COUNT(*) > 5;

[User] Sort the results by avg_name_length descending.

[Assistant] SELECT security_type, COUNT(*) AS securities_count, AVG(LENGTH(security_name)) AS avg_name_length FROM financial_services.securities GROUP BY security_type HAVING COUNT(*) > 5 ORDER BY avg_name_length DESC;

[User] For each patient, find the next appointment after each one. Return patient_id, appointment_id AS current_appointment, next_appointment_id, and waiting_time in minutes.

[Assistant]
SELECT a.patient_id,
       a.appointment_id AS current_appointment,
       b.appointment_id AS next_appointment_id,
       EXTRACT(EPOCH FROM (b.appointment_time - a.appointment_time)) / 60 AS waiting_time
FROM healthcare.appointments a
JOIN healthcare.appointments b
  ON a.patient_id = b.patient_id
 AND b.appointment_time = (
     SELECT MIN(appointment_time)
     FROM healthcare.appointments
     WHERE patient_id = a.patient_id
       AND appointment_time > a.appointment_time
 ) ;

[User] Only include waiting times less than 30 minutes.

[Assistant]
SELECT a.patient_id,
       a.appointment_id AS current_appointment,
       b.appointment_id AS next_appointment_id,
       EXTRACT(EPOCH FROM (b.appointment_time - a.appointment_time)) / 60 AS waiting_time
FROM healthcare.appointments a
JOIN healthcare.appointments b
  ON a.patient_id = b.patient_id
 AND b.appointment_time = (
     SELECT MIN(appointment_time)
     FROM healthcare.appointments
     WHERE patient_id = a.patient_id
       AND appointment_time > a.appointment_time
 )
WHERE EXTRACT(EPOCH FROM (b.appointment_time - a.appointment_time)) / 60 < 30;

[User] Can you list all the room types and their base rates along with the maximum occupancy for each property?

[Assistant] SELECT property_id, type_name, base_rate, max_occupancy FROM hospitality_technology.room_types;

[User] Show only those room types that can accommodate more than 4 people and have a base rate above 200. Order the results by base rate.

[Assistant] SELECT property_id, type_name, base_rate, max_occupancy FROM hospitality_technology.room_types WHERE max_occupancy > 4 AND base_rate > 200 ORDER BY base_rate;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement. ##Table Structure
CREATE TABLE hospitality_technology.rooms ( room_id text, property_id text, room_number text, room_type_id text, floor integer, status text, is_smoking boolean, features text, current_condition text, last_cleaned_at timestamp )
CREATE TABLE hospitality_technology.room_types ( room_type_id text, property_id text, type_name text, description text, base_rate numeric, max_occupancy integer, bed_type text, area_sqft numeric, amenities text )
CREATE TABLE hospitality_technology.guests ( guest_id text, first_name text, last_name text, email text, phone_number text, date_of_birth date, address_line1 text, city text, state_province text, postal_code text, country_code text, preferences text, loyalty_member_id text, communication_consent boolean, created_at timestamp, updated_at timestamp )
CREATE TABLE hospitality_technology.reservations ( reservation_id text, property_id text, guest_id text, room_id text, room_type_id text, check_in_date date, check_out_date date, actual_check_in_ts timestamp, actual_check_out_ts timestamp, num_adults integer, num_children integer, status text, booking_source text, rate_plan_id text, total_amount numeric, amount_paid numeric, special_requests text, created_at timestamp, updated_at timestamp )
CREATE TABLE hospitality_technology.staff ( staff_id text, property_id text, first_name text, last_name text, position text, work_email text, work_phone text, hire_date date, termination_date date, is_active boolean, access_level integer, manager_id text, created_at timestamp )
CREATE TABLE hospitality_technology.services ( service_id text, property_id text, service_name text, description text, category text, price numeric, unit text, is_available boolean, department text )
CREATE TABLE hospitality_technology.payments ( payment_id text, reservation_id text, guest_id text, bill_id text, amount numeric, currency_code text, payment_method text, card_type text, card_last_four text, transaction_ref text, payment_timestamp timestamp, status text, staff_id_processed text, notes text )
CREATE TABLE hospitality_technology.reviews ( review_id text, property_id text, reservation_id text, guest_id text, rating_overall integer, rating_cleanliness integer, rating_service integer, rating_location integer, rating_value integer, comment text, review_source text, review_date timestamp, is_public boolean, staff_response text, response_staff_id text, response_date timestamp )
##Table Structure
CREATE TABLE financial_services.market_data ( data_point_id bigserial NOT NULL, security_id character varying(64) NOT NULL, data_timestamp timestamp NOT NULL, open_price numeric(19, 8), high_price numeric(19, 8), low_price numeric(19, 8), close_price numeric(19, 8) NOT NULL, adjusted_close_price numeric(19, 8), volume bigint, source character varying(50), PRIMARY KEY (data_point_id), UNIQUE (security_id, data_timestamp), FOREIGN KEY (security_id) REFERENCES financial_services.securities(security_id) )
##Table Structure
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 project_fundraising_record ( id character varying(32) NOT NULL,  -- fundraising record id project_id character varying(32) NOT NULL, -- the invested project's id project_name character varying(128) NOT NULL, -- name of the invested project rounds_name character varying(32), -- name of the fundraising round investment_value numeric(38,14), -- amount of the fundraising in USD investment_date character varying(128), -- the date of the investment happened introduction character varying(128), -- the introduction of the invested project valuation numeric(38,14), -- the valuation of the project in USD when invested )
##Table Structure
CREATE TABLE social_media.follows ( follow_id.text, follower_user_id.text, following_user_id.text, created_at.timestamp )

[User] Show me the count of rooms by status.

[Assistant]
SELECT status,
       COUNT(*) AS room_count
FROM hospitality_technology.rooms
GROUP BY status;

[User] Actually, I need that breakdown by property as well.

[Assistant]
SELECT property_id,
       status,
       COUNT(*) AS room_count
FROM hospitality_technology.rooms
GROUP BY property_id, status
ORDER BY property_id, status;

[User] Provide for each security its ticker_symbol, the most recent close_price and corresponding timestamp.

[Assistant]
SELECT s.ticker_symbol, md.close_price, md.data_timestamp
FROM financial_services.market_data md
JOIN financial_services.securities s ON md.security_id = s.security_id
WHERE md.data_timestamp = (
  SELECT MAX(md2.data_timestamp)
  FROM financial_services.market_data md2
  WHERE md2.security_id = md.security_id
);

[User] Actually, I'd like to filter to only those securities where the latest adjusted_close_price is at least 2% higher than the previous data point.

[Assistant]
WITH ranked AS (
  SELECT md.security_id, s.ticker_symbol, md.data_timestamp, md.adjusted_close_price,
         LAG(md.adjusted_close_price) OVER (PARTITION BY md.security_id ORDER BY md.data_timestamp) AS prev_adj
  FROM financial_services.market_data md
  JOIN financial_services.securities s ON md.security_id = s.security_id
)
SELECT r.ticker_symbol, r.data_timestamp AS latest_timestamp, r.adjusted_close_price
FROM ranked r
WHERE r.data_timestamp = (
    SELECT MAX(r2.data_timestamp) FROM ranked r2 WHERE r2.security_id = r.security_id
  )
  AND r.adjusted_close_price >= r.prev_adj * 1.02;

[User] The SQL gives errors about ambiguous column names. Please fully qualify all columns and table aliases.

[Assistant]
WITH ranked AS (
  SELECT md.security_id, s.ticker_symbol, md.data_timestamp, md.adjusted_close_price,
         LAG(md.adjusted_close_price) OVER (PARTITION BY md.security_id ORDER BY md.data_timestamp) AS prev_adj
  FROM financial_services.market_data AS md
  JOIN financial_services.securities AS s ON md.security_id = s.security_id
)
SELECT ranked.ticker_symbol,
       ranked.data_timestamp AS latest_timestamp,
       ranked.adjusted_close_price
FROM ranked
WHERE ranked.data_timestamp = (
    SELECT MAX(r2.data_timestamp)
    FROM ranked AS r2
    WHERE r2.security_id = ranked.security_id
  )
  AND ranked.adjusted_close_price >= ranked.prev_adj * 1.02;

[User] Get a list of users who have both read and unread notifications. For each user, show their user_id, the count of unread notifications as unread_count, and the count of read notifications as read_count.

[Assistant]
SELECT unread.user_id, unread.unread_count, read_counts.read_count
FROM (
  SELECT user_id, COUNT(*) AS unread_count
  FROM trading_platform.notifications
  WHERE read_at IS NULL
  GROUP BY user_id
) AS unread
JOIN (
  SELECT user_id, COUNT(*) AS read_count
  FROM trading_platform.notifications
  WHERE read_at IS NOT NULL
  GROUP BY user_id
) AS read_counts
ON unread.user_id = read_counts.user_id;

[User] Actually, I want to filter to only include those users whose unread_count is at least 3.

[Assistant]
SELECT unread.user_id, unread.unread_count, read_counts.read_count
FROM (
  SELECT user_id, COUNT(*) AS unread_count
  FROM trading_platform.notifications
  WHERE read_at IS NULL
  GROUP BY user_id
  HAVING COUNT(*) >= 3
) AS unread
JOIN (
  SELECT user_id, COUNT(*) AS read_count
  FROM trading_platform.notifications
  WHERE read_at IS NOT NULL
  GROUP BY user_id
) AS read_counts
ON unread.user_id = read_counts.user_id;

[User] For projects that have completed more than one fundraising round, calculate the average investment value across all their recorded rounds. Display the project name and this average value.

[Assistant] SELECT project_name, AVG(investment_value) AS average_investment FROM project_fundraising_record GROUP BY project_name HAVING COUNT(*) > 1;

[User] Can you modify this to only show projects where the average investment value is greater than 10 million USD and order the results by average investment value descending?

[Assistant] SELECT project_name, AVG(investment_value) AS average_investment FROM project_fundraising_record GROUP BY project_name HAVING COUNT(*) > 1 AND AVG(investment_value) > 10000000 ORDER BY average_investment DESC;

[User] List all unique pairs of users where one follows the other, showing both the follower and following user ID.

[Assistant]
SELECT DISTINCT follower_user_id, following_user_id
FROM social_media.follows;

[User] Only include pairs where the follower_user_id is alphabetically less than the following_user_id.

[Assistant]
SELECT DISTINCT follower_user_id, following_user_id
FROM social_media.follows
WHERE follower_user_id < following_user_id;