System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement. ##Table Structure
CREATE TABLE hospitality_technology.reviews ( review_id text, property_id text, reservation_id text, guest_id text, rating_overall integer, rating_cleanliness integer, rating_service integer, rating_location integer, rating_value integer, comment text, review_source text, review_date timestamp, is_public boolean, staff_response text, response_staff_id text, response_date timestamp )
##Table Structure
CREATE TABLE trading_platform.assets ( asset_id character varying(64) NOT NULL, name character varying(128) NOT NULL, symbol character varying(32) NOT NULL, type character varying(32) NOT NULL, PRIMARY KEY (asset_id) )
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.kyc_audit ( kyc_audit_id character varying(64) NOT NULL, user_id character varying(64) NOT NULL, status character varying(32) NOT NULL, reviewed_at timestamp NOT NULL, PRIMARY KEY (kyc_audit_id) )
##Table Structure
CREATE TABLE government_services.employees ( employee_id.text, agency_id.text, first_name.text, last_name.text, job_title.text, department.text, work_email.text, work_phone.text, hire_date.date, termination_date.date, access_level.text, manager_employee_id.text )
##Table Structure
CREATE TABLE government_services.citizens ( citizen_id text PRIMARY KEY, national_id_number text, first_name text, last_name text, date_of_birth date, gender text, primary_address text, contact_email text, contact_phone text, registration_date timestamp, is_verified boolean )
##Table Structure
CREATE TABLE 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 )
##Table Structure
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 )
##Table Structure
CREATE TABLE social_media.users ( user_id text, username text, email text, password_hash text, full_name text, profile_picture_url text, bio text, location text, created_at timestamp, updated_at timestamp, is_verified boolean )
CREATE TABLE social_media.posts ( post_id text, user_id text, content text, media_url text, media_type text, created_at timestamp, updated_at timestamp, visibility text, location_lat numeric, location_lon numeric )
CREATE TABLE social_media.likes ( like_id character varying(64) NOT NULL, user_id character varying(64) NOT NULL, post_id character varying(64), comment_id character varying(64), created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, PRIMARY KEY (like_id), CONSTRAINT unique_user_like UNIQUE (user_id, post_id, comment_id), CONSTRAINT check_like_target CHECK (post_id IS NOT NULL OR comment_id IS NOT NULL) )
CREATE TABLE social_media.follows ( follow_id.text, follower_user_id.text, following_user_id.text, created_at.timestamp )
CREATE TABLE social_media.conversation_participants ( participant_id.text, conversation_id.text, user_id.text, joined_at.timestamp, last_read_at.timestamp )
CREATE TABLE social_media.notifications ( notification_id text PRIMARY KEY, recipient_user_id text, sender_user_id text, notification_type text, target_entity_id text, target_entity_type text, created_at timestamp, read_at timestamp )
CREATE TABLE social_media.user_settings ( setting_id text 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 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 web3.token_transfers ( transfer_id text PRIMARY KEY, token_id text, from_address text, to_address text, value numeric, transaction_id text, log_index int )

[User] Show me each staff member by response_staff_id and the number of unique guests whose reviews they have responded to.

[Assistant]
SELECT response_staff_id, COUNT(DISTINCT guest_id) AS unique_guest_count
FROM hospitality_technology.reviews
WHERE response_staff_id IS NOT NULL
GROUP BY response_staff_id;

[User] Show a list of all asset names along with the current KYC status of each user, including the asset symbol. Join the assets and kyc_audit tables.

[Assistant]
SELECT a.name AS asset_name, a.symbol, k.user_id, k.status AS kyc_status
FROM trading_platform.assets a
JOIN trading_platform.kyc_audit k ON 1=1

[User] I only want the result for users whose KYC status is 'approved' and for assets where the symbol is at least 3 characters long.

[Assistant]
SELECT a.name AS asset_name, a.symbol, k.user_id, k.status AS kyc_status
FROM trading_platform.assets a
JOIN trading_platform.kyc_audit k ON 1=1
WHERE k.status = 'approved' AND LENGTH(a.symbol) >= 3

[User] List all employees whose job titles differ from their direct managers. Provide each employee's full name, their job title, the manager's full name, and the manager's job title.

[Assistant] SELECT e.first_name || ' ' || e.last_name AS employee_name, e.job_title AS employee_job_title, m.first_name || ' ' || m.last_name AS manager_name, m.job_title AS manager_job_title FROM government_services.employees e JOIN government_services.employees m ON e.manager_employee_id = m.employee_id WHERE e.job_title <> m.job_title;

[User] Find all male-female citizen pairs born in the same year. Display the male's full name, the female's full name, and their shared birth year.

[Assistant]
SELECT
  m.first_name || ' ' || m.last_name AS male_full_name,
  f.first_name || ' ' || f.last_name AS female_full_name,
  EXTRACT(YEAR FROM m.date_of_birth) AS birth_year
FROM government_services.citizens m
JOIN government_services.citizens f
  ON EXTRACT(YEAR FROM m.date_of_birth) = EXTRACT(YEAR FROM f.date_of_birth)
     AND m.gender = 'Male'
     AND f.gender = 'Female';

[User] How many reservations does each property have?

[Assistant]
SELECT property_id,
       COUNT(*) AS reservation_count
FROM hospitality_technology.reservations
GROUP BY property_id;

[User] Actually, only count reservations with status 'CheckedOut' or 'Completed'.

[Assistant]
SELECT property_id,
       COUNT(*) AS reservation_count
FROM hospitality_technology.reservations
WHERE status IN ('CheckedOut', 'Completed')
GROUP BY property_id;

[User] List all room types along with the name of the property they belong to. Show the room type name, property name, and base rate.

[Assistant] SELECT t1.type_name, t2.property_name, t1.base_rate FROM hospitality_technology.room_types AS t1 JOIN hospitality_technology.properties AS t2 ON t1.property_id = t2.property_id

[User] List the users who have never posted any public posts, showing user_id, username, and email.

[Assistant] SELECT u.user_id, u.username, u.email FROM social_media.users u LEFT JOIN social_media.posts p ON p.user_id = u.user_id AND p.visibility = 'public' WHERE p.post_id IS NULL;

[User] List all pending premium payments made in March 2024, showing payment_id, customer_id, amount_paid, and due_date, ordered by payment_date ascending.

[Assistant]
SELECT payment_id,
       customer_id,
       amount_paid,
       due_date
FROM insurance.premium_payments
WHERE status = 'pending'
  AND payment_date >= '2024-03-01'
  AND payment_date < '2024-04-01'
ORDER BY payment_date ASC;

[User] List the top 5 addresses that have received the most token transfers.

[Assistant] SELECT to_address, COUNT(*) AS transfer_count FROM web3.token_transfers GROUP BY to_address ORDER BY transfer_count DESC LIMIT 5;

[User] Okay, but only for token_id '0xabc123...' and also show the total value received by each of these addresses for that token.

[Assistant] SELECT to_address, COUNT(*) AS transfer_count, SUM(value) AS total_received_value FROM web3.token_transfers WHERE token_id = '0xabc123...' GROUP BY to_address ORDER BY transfer_count DESC LIMIT 5;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement. ##Table Structure
CREATE TABLE insurance.claim_documents (
    document_id character varying(64) NOT NULL, -- unique identifier for the document
    claim_id character varying(64) NOT NULL, -- identifier of the claim this document relates to (FK to claims)
    document_type character varying(50) NOT NULL, -- e.g., Police Report, Photo, Invoice, Medical Bill
    file_name character varying(255) NOT NULL, -- original name of the uploaded file
    file_path character varying(512) NOT NULL, -- storage path (e.g., S3 URL, network path)
    file_size_bytes integer, -- size of the file in bytes
    mime_type character varying(100), -- MIME type of the file (e.g., 'image/jpeg', 'application/pdf')
    uploaded_by character varying(64), -- identifier of the user/system who uploaded (FK to users/customers)
    uploaded_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, -- time of upload
    description text, -- optional description of the document
    PRIMARY KEY (document_id)
)
##Table Structure
CREATE TABLE healthcare.medications ( medication_id.text, medication_name.text, generic_name.text, manufacturer.text, ndc_code.text, description.text )
##Table Structure
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)
)
##Table Structure
CREATE TABLE web3.events ( event_id.text, contract_id.text, event_name.text, data.text, emitted_at.timestamp, transaction_id.text, log_index.integer )
CREATE TABLE web3.transactions ( transaction_id text PRIMARY KEY, from_address text, to_address text, value numeric, gas_used int, gas_price numeric, block_number int, timestamp timestamp, input_data text, status text, nonce int )
CREATE TABLE web3.token_transfers (
    transfer_id character varying(64) NOT NULL,  -- unique identifier for the transfer
    token_id character varying(64) NOT NULL, -- identifier of the token being transferred
    from_address character varying(128) NOT NULL, -- address of the sender
    to_address character varying(128) NOT NULL, -- address of the receiver
    value numeric(38,14) NOT NULL, -- amount of tokens transferred
    transaction_id character varying(64) NOT NULL, -- identifier of the transaction containing the transfer
    log_index integer NOT NULL, -- index of the transfer log in the transaction
    PRIMARY KEY (transfer_id)
)
CREATE TABLE web3.users ( user_id text, username text, email text, password_hash text, created_at timestamp )
##Table Structure
CREATE TABLE social_media.messages ( message_id character varying(64) NOT NULL, conversation_id character varying(64) NOT NULL, sender_user_id character varying(64) NOT NULL, content text, media_url text, media_type character varying(20), sent_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, read_at timestamp, PRIMARY KEY (message_id) )
##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 )
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 transportation.routes ( route_id.text, route_number.text, description.text, origin_location_id.text, destination_location_id.text, distance_km.numeric, estimated_duration_minutes.integer, type.text )
##Table Structure
CREATE TABLE healthcare.patients ( patient_id text, first_name text, last_name text, date_of_birth date, gender text, address text, phone_number text, email text, emergency_contact_name text, emergency_contact_phone text, created_at timestamp, updated_at timestamp )

[User] For each document type, how many documents were uploaded by each user? Show the uploaded_by, document_type, and document count, ordered by document_type and count descending.

[Assistant]
SELECT uploaded_by, document_type, COUNT(*) AS document_count
FROM insurance.claim_documents
GROUP BY uploaded_by, document_type
ORDER BY document_type ASC, document_count DESC;

[User] Find all medications whose generic_name matches the medication_name of another entry, displaying the brand medication_id, brand medication_name, generic medication_id, and generic medication_name.

[Assistant]
SELECT b.medication_id AS brand_id, b.medication_name AS brand_name, g.medication_id AS generic_id, g.medication_name AS generic_name
FROM healthcare.medications b
JOIN healthcare.medications g
  ON b.generic_name = g.medication_name;

[User] Filter to include only those where the manufacturer of the brand differs from that of the generic match.

[Assistant]
SELECT b.medication_id AS brand_id, b.medication_name AS brand_name, g.medication_id AS generic_id, g.medication_name AS generic_name
FROM healthcare.medications b
JOIN healthcare.medications g
  ON b.generic_name = g.medication_name
WHERE b.manufacturer <> g.manufacturer;

[User] List all customer_ids who have both a checking account and a savings account with a combined balance exceeding $50,000.

[Assistant] SELECT c.customer_id FROM financial_services.accounts c JOIN financial_services.accounts s ON c.customer_id = s.customer_id WHERE c.account_type = 'Checking' AND s.account_type = 'Savings' AND (c.balance + s.balance) > 50000 GROUP BY c.customer_id;

[User] Find all token transfers where the value is greater than 5000, including the token_id and transaction details like from_address and gas_used, sorted by value in descending order.

[Assistant] SELECT tt.token_id, tt.value, t.from_address, t.to_address, t.gas_used, t.block_number, t.timestamp FROM web3.token_transfers tt JOIN web3.transactions t ON tt.transaction_id = t.transaction_id WHERE tt.value > 5000 ORDER BY tt.value DESC;

[User] Show me each sender_user_id along with the total number of messages they have sent in each conversation.

[Assistant] SELECT conversation_id, sender_user_id, COUNT(*) AS message_count FROM social_media.messages GROUP BY conversation_id, sender_user_id;

[User] Only include conversations where a sender has sent at least 5 messages.

[Assistant] SELECT conversation_id, sender_user_id, COUNT(*) AS message_count FROM social_media.messages GROUP BY conversation_id, sender_user_id HAVING COUNT(*) >= 5;

[User] Which clients have appointments scheduled for a case that also has at least one invoice issued? Please show the client_id, appointment_id, appointment start_time, related case_id, and invoice_number.

[Assistant]
SELECT a.client_id, a.appointment_id, a.start_time, a.case_id, i.invoice_number
FROM legal_services.appointments a
JOIN legal_services.invoices i ON a.case_id = i.case_id
WHERE a.status = 'Scheduled';

[User] Find all pairs of distinct routes that share the same origin location ID. List the route IDs and route numbers for both routes in each pair, along with the shared origin location ID.

[Assistant] SELECT r1.route_id AS route1_id, r1.route_number AS route1_number, r2.route_id AS route2_id, r2.route_number AS route2_number, r1.origin_location_id FROM transportation.routes AS r1 JOIN transportation.routes AS r2 ON r1.origin_location_id = r2.origin_location_id WHERE r1.route_id < r2.route_id;

[User] Count the number of patients whose address includes the word 'Street' and are male.

[Assistant] SELECT COUNT(*) FROM healthcare.patients WHERE address LIKE '%Street%' AND gender = 'Male';


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.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 )
CREATE TABLE transportation.fuel_logs ( fuel_log_id text PRIMARY KEY, vehicle_id text, trip_id text, log_timestamp timestamp, fuel_type text, quantity numeric, unit text, cost_per_unit numeric, total_cost numeric, odometer_reading int, location_id text )
CREATE TABLE transportation.bookings ( booking_id text PRIMARY KEY, passenger_id text, trip_id text, seat_number text, booking_time timestamp, status text, fare numeric, payment_transaction_id text, special_requests text )
##Table Structure
CREATE TABLE web3.wallets ( wallet_id text, user_id text, address text, private_key text, created_at timestamp )
##Table Structure
CREATE TABLE transportation.maintenance_logs ( log_id text, vehicle_id text, service_date date, odometer_reading integer, service_type text, description text, cost numeric, mechanic_name text, next_service_due_date date )
##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 web3.events ( event_id.text, contract_id.text, event_name.text, data.text, emitted_at.timestamp, transaction_id.text, log_index.integer )
CREATE TABLE web3.transactions ( transaction_id character varying(64) NOT NULL, from_address character varying(128) NOT NULL, to_address character varying(128), value numeric(38,14) NOT NULL, gas_used integer NOT NULL, gas_price numeric(38,14) NOT NULL, block_number integer NOT NULL, timestamp timestamp NOT NULL, input_data text, status character varying(32) NOT NULL, nonce integer NOT NULL, PRIMARY KEY (transaction_id) )
CREATE TABLE web3.tokens ( token_id.text, contract_address.text, token_name.text, token_symbol.text, decimals.integer, total_supply.numeric )
CREATE TABLE web3.wallets ( wallet_id text, user_id text, address text, private_key text, created_at timestamp )
CREATE TABLE web3.users ( user_id text PRIMARY KEY, username text, email text, password_hash text, created_at timestamp )
##Table Structure
CREATE TABLE gaming_technology.developers (
    developer_id uuid NOT NULL DEFAULT gen_random_uuid(), -- unique identifier for the developer studio
    name character varying(150) NOT NULL UNIQUE, -- name of the development studio
    country character varying(100), -- country where the studio is based
    founded_year integer, -- year the studio was founded
    website character varying(255), -- developer's official website
    created_at timestamp with time zone NOT NULL DEFAULT CURRENT_TIMESTAMP,
    PRIMARY KEY (developer_id)
)
##Table Structure
CREATE TABLE web3.transactions ( transaction_id text, from_address text, to_address text, value numeric, gas_used integer, gas_price numeric, block_number integer, timestamp timestamp, input_data text, status text, nonce integer )

[User] What is the average cost per unit for fuel at each location type? Show the location type and the average cost.

[Assistant] SELECT T2.type ,  AVG(T1.cost_per_unit) FROM transportation.fuel_logs AS T1 JOIN transportation.locations AS T2 ON T1.location_id  =  T2.location_id GROUP BY T2.type

[User] Which user has the earliest created wallet? Show the user_id, wallet_id, address, and the creation timestamp.

[Assistant]
SELECT user_id, wallet_id, address, created_at
FROM web3.wallets
ORDER BY created_at ASC
LIMIT 1;

[User] Can you show all users whose earliest wallet was created on '2023-01-01'? Please include their user_id, wallet_id, and wallet address.

[Assistant]
SELECT w.user_id, w.wallet_id, w.address
FROM web3.wallets w
INNER JOIN (
  SELECT user_id, MIN(created_at) AS min_created_at
  FROM web3.wallets
  GROUP BY user_id
) first_wallet ON w.user_id = first_wallet.user_id AND w.created_at = first_wallet.min_created_at
WHERE w.created_at::date = '2023-01-01';

[User] List each vehicle and the date of its most recent maintenance, including the service type and cost.

[Assistant] SELECT vehicle_id, service_type, cost, service_date FROM (SELECT *, ROW_NUMBER() OVER (PARTITION BY vehicle_id ORDER BY service_date DESC) AS rn FROM transportation.maintenance_logs) AS ranked_logs WHERE rn = 1;

[User] I received an error that 'service_type' does not exist in the outermost query.

[Assistant] SELECT vehicle_id, service_date, service_type, cost FROM (SELECT log_id, vehicle_id, service_date, service_type, cost, ROW_NUMBER() OVER (PARTITION BY vehicle_id ORDER BY service_date DESC) AS rn FROM transportation.maintenance_logs) AS ranked_logs WHERE rn = 1;

[User] Also include the name of the mechanic for each latest maintenance.

[Assistant] SELECT vehicle_id, service_date, service_type, cost, mechanic_name FROM (SELECT log_id, vehicle_id, service_date, service_type, cost, mechanic_name, ROW_NUMBER() OVER (PARTITION BY vehicle_id ORDER BY service_date DESC) AS rn FROM transportation.maintenance_logs) AS ranked_logs WHERE rn = 1;

[User] For each employee, retrieve their full name and the number of appointments scheduled for them in the next 7 days, including employees with no appointments.

[Assistant]
SELECT e.first_name || ' ' || e.last_name AS full_name,
       COUNT(a.appointment_id) AS appointment_count
FROM government_services.employees e
LEFT JOIN government_services.appointments a
  ON e.employee_id = a.employee_id
  AND a.scheduled_start_time BETWEEN now() AND now() + INTERVAL '7 days'
GROUP BY e.first_name, e.last_name;

[User] Find all users and the total value of transactions they have received, showing user_id, username, and total_received_value.

[Assistant]
SELECT u.user_id,
       u.username,
       COALESCE(SUM(t.value), 0) AS total_received_value
FROM web3.users u
LEFT JOIN web3.wallets w
  ON u.user_id = w.user_id
LEFT JOIN web3.transactions t
  ON t.to_address = w.address
GROUP BY u.user_id, u.username;

[User] How many developers are there in each country?

[Assistant]
SELECT
  country,
  COUNT(developer_id) AS developer_count
FROM
  gaming_technology.developers
WHERE country IS NOT NULL
GROUP BY
  country;

[User] Only include countries with more than 5 developers.

[Assistant]
SELECT
  country,
  COUNT(developer_id) AS developer_count
FROM
  gaming_technology.developers
WHERE country IS NOT NULL
GROUP BY
  country
HAVING
  COUNT(developer_id) > 5;

[User] Count the number of transactions for each status.

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

[User] Actually, only include statuses with more than 1000 transactions.

[Assistant]
SELECT status, COUNT(*) AS tx_count
FROM web3.transactions
GROUP BY status
HAVING COUNT(*) > 1000;


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.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 )
##Table Structure
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)
)
##Table Structure
CREATE TABLE healthcare.patient_insurance ( patient_insurance_id character varying(64) NOT NULL, patient_id character varying(64) NOT NULL, plan_id character varying(64) NOT NULL, policy_number character varying(100) NOT NULL, group_number character varying(100), subscriber_name character varying(200), effective_date date NOT NULL, expiration_date date, is_primary boolean NOT NULL DEFAULT true, PRIMARY KEY (patient_insurance_id), UNIQUE (patient_id, plan_id, policy_number) )
##Table Structure
CREATE TABLE trading_platform.assets ( asset_id character varying(64) NOT NULL, name character varying(128) NOT NULL, symbol character varying(32) NOT NULL, type character varying(32) NOT NULL, PRIMARY KEY (asset_id) )
CREATE TABLE trading_platform.utxos ( utxo_id.text, transaction_id.text, output_index.integer, address.text, amount.numeric, spent.boolean )
##Table Structure
CREATE TABLE social_media.posts ( post_id.text, user_id.text, content.text, media_url.text, media_type.text, created_at.timestamp, updated_at.timestamp, visibility.text, location_lat.numeric, location_lon.numeric )
CREATE TABLE social_media.follows ( follow_id text PRIMARY KEY, follower_user_id text, following_user_id text, created_at timestamp )
CREATE TABLE social_media.conversation_participants ( participant_id text PRIMARY KEY, conversation_id text, user_id text, joined_at timestamp, last_read_at timestamp )
CREATE TABLE social_media.user_settings ( setting_id.text, user_id.text, theme.text, email_notifications_enabled.boolean, push_notifications_enabled.boolean, private_profile.boolean, updated_at.timestamp )
##Table Structure
CREATE TABLE insurance.agents ( agent_id.text, first_name.text, last_name.text, agency_name.text, license_number.text, license_state.text, contact_email.text, contact_phone.text, hire_date.date, termination_date.date, status.text, commission_rate.numeric, manager_id.text )
##Table Structure
CREATE TABLE web3.transactions ( transaction_id character varying(64) NOT NULL, from_address character varying(128) NOT NULL, to_address character varying(128), value numeric(38,14) NOT NULL, gas_used integer NOT NULL, gas_price numeric(38,14) NOT NULL, block_number integer NOT NULL, timestamp timestamp NOT NULL, input_data text, status character varying(32) NOT NULL, nonce integer NOT NULL, PRIMARY KEY (transaction_id) )
##Table Structure
CREATE TABLE web3.events ( event_id.text, contract_id.text, event_name.text, data.text, emitted_at.timestamp, transaction_id.text, log_index.integer )
CREATE TABLE web3.transactions ( transaction_id character varying(64) NOT NULL, from_address character varying(128) NOT NULL, to_address character varying(128), value numeric(38,14) NOT NULL, gas_used integer NOT NULL, gas_price numeric(38,14) NOT NULL, block_number integer NOT NULL, timestamp timestamp NOT NULL, input_data text, status character varying(32) NOT NULL, nonce integer NOT NULL, PRIMARY KEY (transaction_id) )
CREATE TABLE web3.tokens ( token_id.text, contract_address.text, token_name.text, token_symbol.text, decimals.integer, total_supply.numeric )
CREATE TABLE web3.wallets ( wallet_id text, user_id text, address text, private_key text, created_at timestamp )
CREATE TABLE web3.users ( user_id text PRIMARY KEY, username text, email text, password_hash text, created_at timestamp )
##Table Structure
CREATE TABLE healthcare.doctors ( doctor_id text, first_name text, last_name text, specialty text, license_number text, phone_number text, email text, hospital_affiliation_id text, created_at timestamp, updated_at timestamp )

[User] List all payments made using a credit card, including guest_id, amount, payment_method, and payment_timestamp.

[Assistant] SELECT guest_id, amount, payment_method, payment_timestamp FROM hospitality_technology.payments WHERE payment_method = 'CreditCard';

[User] Could you also include the last four digits of the card used for each payment?

[Assistant] SELECT guest_id, amount, payment_method, card_last_four, payment_timestamp FROM hospitality_technology.payments WHERE payment_method = 'CreditCard';

[User] For each address, show the total amount contained in UTXOs that have been spent.

[Assistant] SELECT address, SUM(amount) FROM utxos WHERE spent = TRUE GROUP BY address;

[User] Only include addresses where this total spent amount is greater than 500 and order the results by the total amount descending.

[Assistant] SELECT address, SUM(amount) FROM utxos WHERE spent = TRUE GROUP BY address HAVING SUM(amount) > 500 ORDER BY SUM(amount) DESC;

[User] Give me the number of patient insurance policies for each plan where the policy is currently active. Return plan_id and policy_count.

[Assistant]
SELECT
  plan_id,
  COUNT(*) AS policy_count
FROM healthcare.patient_insurance
WHERE (expiration_date IS NULL OR expiration_date >= CURRENT_DATE)
GROUP BY plan_id;

[User] Now, only include plans where the count is greater than 5 and sort by policy_count descending.

[Assistant]
SELECT
  plan_id,
  COUNT(*) AS policy_count
FROM healthcare.patient_insurance
WHERE (expiration_date IS NULL OR expiration_date >= CURRENT_DATE)
GROUP BY plan_id
HAVING COUNT(*) > 5
ORDER BY policy_count DESC;

[User] List all UTXO IDs, addresses, and amounts for unspent UTXOs with an amount between 200 and 800.

[Assistant] SELECT utxo_id, address, amount FROM trading_platform.utxos WHERE spent = false AND amount BETWEEN 200 AND 800;

[User] Count the number of unique users who are being followed.

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

[User] List each agent along with their manager's contact_email. Include agent_id, first_name, last_name, manager_id, and manager's contact_email.

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

[User] Actually, only include records where the manager is currently active.

[Assistant]
SELECT a.agent_id,
       a.first_name,
       a.last_name,
       a.manager_id,
       m.contact_email AS manager_contact_email
FROM insurance.agents a
LEFT JOIN insurance.agents m
  ON a.manager_id = m.agent_id
WHERE m.status = 'active';

[User] Find all transactions where the from_address is the same as the to_address, indicating self-transactions, and show the transaction_id, value, and gas_used.

[Assistant] SELECT transaction_id, value, gas_used FROM web3.transactions WHERE from_address = to_address;

[User] For each user, list their username, the number of wallets they have, and the total gas used across all transactions they initiated.

[Assistant]
SELECT u.username,
       COUNT(w.wallet_id) AS wallet_count,
       COALESCE(SUM(t.gas_used), 0) AS total_gas_used
FROM web3.users u
LEFT JOIN web3.wallets w
  ON u.user_id = w.user_id
LEFT JOIN web3.transactions t
  ON t.from_address = w.address
GROUP BY u.username;

[User] Show the license numbers and full names of all doctors who were registered before January 1, 2020 and work at 'hospital_789'.

[Assistant] SELECT license_number, first_name, last_name FROM healthcare.doctors WHERE created_at < '2020-01-01' AND hospital_affiliation_id = 'hospital_789';


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement. ##Table Structure
Use Hashes. Key pattern: 'component:<component_id>'. Example: HSET component:LGSTRUT01 part_number "PN-5521-A" component_name "Landing Gear Strut" material_id "mat:TI64" supplier_id "sup:ACME_AERO" ... Consider Sets for reverse lookups (e.g., 'material_components:<material_id>' -> Set<component_id>).
##Table Structure
CREATE TABLE web3.contracts ( contract_id.text, address.text, abi.text, bytecode.text, deployer_address.text, deployed_at.timestamp, network_id.text, status.text )
CREATE TABLE web3.events ( event_id.text, contract_id.text, event_name.text, data.text, emitted_at.timestamp, transaction_id.text, log_index.integer )
CREATE TABLE web3.token_transfers ( transfer_id.text, token_id.text, from_address.text, to_address.text, value.numeric, transaction_id.text, log_index.integer )
CREATE TABLE web3.wallets ( wallet_id.text, user_id.text, address.text, private_key.text, created_at.timestamp )
CREATE TABLE web3.users ( user_id.text, username.text, email.text, password_hash.text, created_at.timestamp )
##Table Structure
CREATE TABLE legal_services.invoices (
    invoice_id character varying(64) NOT NULL,  -- unique identifier for the invoice
    invoice_number character varying(100) UNIQUE NOT NULL, -- user-facing invoice number
    client_id character varying(64) NOT NULL, -- FK to clients table
    case_id character varying(64), -- FK to cases table (optional, could be general retainer)
    issue_date date NOT NULL, -- date the invoice was generated
    due_date date NOT NULL, -- date the payment is due
    total_amount numeric(12, 2) NOT NULL, -- total amount due on the invoice
    amount_paid numeric(12, 2) DEFAULT 0.00, -- amount already paid
    status character varying(50) NOT NULL, -- e.g., Draft, Sent, Paid, Partially Paid, Overdue, Void
    payment_date timestamp, -- date the invoice was fully paid (nullable)
    notes text, -- additional notes or terms on the invoice
    created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
    PRIMARY KEY (invoice_id)
)
##Table Structure
CREATE TABLE trading_platform.orders ( order_id text PRIMARY KEY, user_id text, wallet_id text, asset_id text, order_type text, quantity numeric, price numeric, status text, created_at timestamp )
CREATE TABLE trading_platform.kyc_audit ( kyc_audit_id text PRIMARY KEY, user_id text, status text, reviewed_at timestamp )
CREATE TABLE trading_platform.logs ( log_id text PRIMARY KEY, user_id text, action text, details text, logged_at timestamp )
CREATE TABLE trading_platform.notifications ( notification_id text PRIMARY KEY, user_id text, message text, sent_at timestamp, read_at timestamp )
##Table Structure
CREATE TABLE trading_platform.users ( user_id text PRIMARY KEY, username text, email text, password_hash text, created_at timestamp )
CREATE TABLE trading_platform.wallets ( wallet_id text PRIMARY KEY, user_id text, address text, private_key text, created_at timestamp )
CREATE TABLE trading_platform.orders ( order_id text PRIMARY KEY, user_id text, wallet_id text, asset_id text, order_type text, quantity numeric, price numeric, status text, created_at timestamp )
CREATE TABLE trading_platform.trades ( trade_id text PRIMARY KEY, order_id text, buyer_id text, seller_id text, asset_id text, quantity numeric, price numeric, traded_at timestamp )
CREATE TABLE trading_platform.utxos ( utxo_id text PRIMARY KEY, transaction_id text, output_index int, address text, amount numeric, spent boolean )
CREATE TABLE trading_platform.dapps ( dapp_id text PRIMARY KEY, name text, description text, url text )
CREATE TABLE trading_platform.peers ( peer_id text PRIMARY KEY, ip_address text, port int, last_seen timestamp )
CREATE TABLE trading_platform.metadata ( metadata_id text PRIMARY KEY, asset_id text, key text, value text )
CREATE TABLE trading_platform.kyc_audit ( kyc_audit_id text PRIMARY KEY, user_id text, status text, reviewed_at timestamp )
CREATE TABLE trading_platform.logs ( log_id text PRIMARY KEY, user_id text, action text, details text, logged_at timestamp )
CREATE TABLE trading_platform.notifications ( notification_id text PRIMARY KEY, user_id text, message text, sent_at timestamp, read_at timestamp )
##Table Structure
CREATE TABLE project_fundraising_record ( id character varying(32) NOT NULL, project_id character varying(32) NOT NULL, project_name character varying(128) NOT NULL, rounds_name character varying(32), investment_value numeric(38,14), investment_date character varying(128), introduction character varying(128), valuation numeric(38,14) )
##Table Structure
CREATE TABLE hospitality_technology.service_orders ( order_id text PRIMARY KEY, reservation_id text, guest_id text, service_id text, staff_id_ordered text, staff_id_delivered text, order_timestamp timestamp, delivery_timestamp timestamp, quantity int, unit_price numeric, total_price numeric, status text, notes text, bill_id text )

[User] Can you help me get a list of components and their associated materials, including the supplier information for each component?

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

[User] Can you filter this to show only components from a specific material ID?

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

[User] What if I want to see only components from a specific supplier as well?

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

[User] Can you also include the component name and sort the results by component name?

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

[User] Find the usernames of users who have deployed contracts and list the address of the contract they deployed.

[Assistant] SELECT T1.username, T3.address FROM web3.users AS T1 JOIN web3.wallets AS T2 ON T1.user_id = T2.user_id JOIN web3.contracts AS T3 ON T2.address = T3.deployer_address;

[User] Show me all invoices, displaying their invoice number and the payment date, for invoices that have been fully paid.

[Assistant] SELECT invoice_number, payment_date FROM legal_services.invoices WHERE status = 'Paid';

[User] Show me all users who have both placed orders and have KYC status approved, along with their order count and most recent KYC review date.

[Assistant] SELECT o.user_id, COUNT(o.order_id) as order_count, MAX(k.reviewed_at) as last_kyc_review FROM trading_platform.orders o JOIN trading_platform.kyc_audit k ON o.user_id = k.user_id WHERE k.status = 'approved' GROUP BY o.user_id;

[User] List each wallet with its wallet_id, user_id, and the total amount of unspent UTXOs associated with that wallet.

[Assistant]
SELECT
  w.wallet_id,
  w.user_id,
  COALESCE(SUM(u.amount), 0) AS unspent_total
FROM trading_platform.wallets w
LEFT JOIN trading_platform.utxos u
  ON w.address = u.address
  AND u.spent = false
GROUP BY w.wallet_id, w.user_id;

[User] Count how many fundraising rounds each project has. Show project_name and round_count.

[Assistant]
SELECT
  project_name,
  COUNT(*) AS round_count
FROM project_fundraising_record
GROUP BY project_name;

[User] Also filter to include only projects with more than 3 rounds and order by round_count descending.

[Assistant]
SELECT
  project_name,
  COUNT(*) AS round_count
FROM project_fundraising_record
GROUP BY project_name
HAVING COUNT(*) > 3
ORDER BY round_count DESC;

[User] Show me the total quantity and total price for each service ordered by each guest.

[Assistant] SELECT guest_id, service_id, SUM(quantity) AS total_quantity, SUM(total_price) AS total_price FROM hospitality_technology.service_orders GROUP BY guest_id, service_id;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement. ##Table Structure
CREATE TABLE government_services.agencies ( agency_id.text, agency_name.text, jurisdiction_level.text, primary_contact_email.text, main_phone_number.text, website_url.text, established_date.date, parent_agency_id.text )
##Table Structure
CREATE TABLE web3.transactions ( transaction_id.text, from_address.text, to_address.text, value.numeric, gas_used.integer, gas_price.numeric, block_number.integer, timestamp.timestamp, input_data.text, status.text, nonce.integer )
##Table Structure
CREATE TABLE legal_services.law_firms ( firm_id text PRIMARY KEY, firm_name text, address text, phone text, website text, founded_date date, managing_partner_id text )
CREATE TABLE legal_services.cases ( case_id text PRIMARY KEY, case_number text UNIQUE, case_name text, client_id text, lead_lawyer_id text, case_type text, status text, date_opened timestamp, date_closed timestamp, description text, court_jurisdiction text )
##Table Structure
CREATE TABLE social_media.users ( user_id text PRIMARY KEY, username text, email text, password_hash text, full_name text, profile_picture_url text, bio text, location text, created_at timestamp, updated_at timestamp, is_verified bool )
##Table Structure
CREATE TABLE government_services.notifications ( notification_id character varying(64) NOT NULL, citizen_id character varying(64) NOT NULL, application_id character varying(64), message_subject character varying(255), message_body text NOT NULL, channel character varying(30) NOT NULL, sent_at timestamp NOT NULL, status character varying(30) NOT NULL, related_entity_type character varying(50), related_entity_id character varying(64), PRIMARY KEY (notification_id) )
##Table Structure
CREATE TABLE government_services.citizens ( citizen_id character varying(64) NOT NULL, national_id_number character varying(128) NOT NULL UNIQUE, first_name character varying(100) NOT NULL, last_name character varying(100) NOT NULL, date_of_birth date NOT NULL, gender character varying(20), primary_address text NOT NULL, contact_email character varying(128) UNIQUE, contact_phone character varying(32), registration_date timestamp NOT NULL, is_verified boolean DEFAULT false, PRIMARY KEY (citizen_id) )
CREATE TABLE government_services.payments ( payment_id character varying(64) NOT NULL, application_id character varying(64), citizen_id character varying(64) NOT NULL, service_id character varying(64), amount numeric(12, 2) NOT NULL, currency character varying(3) NOT NULL DEFAULT 'USD', payment_method character varying(50), payment_provider_reference character varying(128), payment_timestamp timestamp NOT NULL, status character varying(30) NOT NULL, notes text, PRIMARY KEY (payment_id) )
CREATE TABLE government_services.employees ( employee_id character varying(64) NOT NULL, agency_id character varying(64) NOT NULL, first_name character varying(100) NOT NULL, last_name character varying(100) NOT NULL, job_title character varying(150) NOT NULL, department character varying(100), work_email character varying(128) NOT NULL UNIQUE, work_phone character varying(32), hire_date date NOT NULL, termination_date date, access_level character varying(50), manager_employee_id character varying(64), PRIMARY KEY (employee_id) )
CREATE TABLE government_services.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, 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) )
CREATE TABLE government_services.notifications ( notification_id character varying(64) NOT NULL, citizen_id character varying(64) NOT NULL, application_id character varying(64), message_subject character varying(255), message_body text NOT NULL, channel character varying(30) NOT NULL, sent_at timestamp NOT NULL, status character varying(30) NOT NULL, related_entity_type character varying(50), related_entity_id character varying(64), PRIMARY KEY (notification_id) )
##Table Structure
CREATE TABLE web3.transactions ( transaction_id text PRIMARY KEY, from_address text, to_address text, value numeric, gas_used int, gas_price numeric, block_number int, timestamp timestamp, input_data text, status text, nonce int )

[User] I would like to see a list of agencies and the names of their respective parent agencies.

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

[User] Could you only show agencies that actually have a parent agency, and order the result by the agency name?

[Assistant]
SELECT a.agency_id, a.agency_name, p.agency_name AS parent_agency_name
FROM government_services.agencies a
INNER JOIN government_services.agencies p ON a.parent_agency_id = p.agency_id
ORDER BY a.agency_name;

[User] For each sender address that has sent at least 10 transactions, show the address and the total gas used by their transactions.

[Assistant]
SELECT from_address, SUM(gas_used) AS total_gas_used
FROM web3.transactions
GROUP BY from_address
HAVING COUNT(*) >= 10;

[User] Show each law firm's name and the number of cases where its managing partner is the lead attorney.

[Assistant] SELECT T1.firm_name, COUNT(T2.case_id) AS case_count_as_managing_partner FROM law_firms AS T1 JOIN cases AS T2 ON T1.managing_partner_id = T2.lead_lawyer_id GROUP BY T1.firm_name;

[User] Only include firms that have at least 2 such cases.

[Assistant] SELECT T1.firm_name, COUNT(T2.case_id) AS case_count_as_managing_partner FROM law_firms AS T1 JOIN cases AS T2 ON T1.managing_partner_id = T2.lead_lawyer_id GROUP BY T1.firm_name HAVING COUNT(T2.case_id) >= 2;

[User] Show the usernames of users who have used any hashtag in their posts, along with the tag name.

[Assistant] SELECT DISTINCT T1.username, T4.tag_name FROM social_media.users AS T1 JOIN posts AS T2 ON T1.user_id = T2.user_id JOIN post_hashtags AS T3 ON T2.post_id = T3.post_id JOIN hashtags AS T4 ON T3.hashtag_id = T4.hashtag_id;

[User] Only include users who have used hashtags more than 3 times across all their posts.

[Assistant] SELECT T1.username, COUNT(T3.hashtag_id) AS hashtag_usage_count FROM social_media.users AS T1 JOIN posts AS T2 ON T1.user_id = T2.user_id JOIN post_hashtags AS T3 ON T2.post_id = T3.post_id GROUP BY T1.username HAVING COUNT(T3.hashtag_id) > 3;

[User] For each notification, list the next notification sent to the same citizen (if any). Show citizen_id, notification_id, sent_at, next_notification_id, and next_sent_at.

[Assistant]
SELECT
  n1.citizen_id,
  n1.notification_id,
  n1.sent_at,
  n2.notification_id AS next_notification_id,
  n2.sent_at         AS next_sent_at
FROM government_services.notifications n1
LEFT JOIN government_services.notifications n2
  ON n1.citizen_id = n2.citizen_id
  AND n2.sent_at = (
    SELECT MIN(sent_at)
    FROM government_services.notifications n3
    WHERE n3.citizen_id = n1.citizen_id
      AND n3.sent_at > n1.sent_at
  );

[User] Count the number of registered citizens by gender.

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

[User] Show all transactions where the transaction value is greater than the average value of all transactions, including transaction_id, from_address, to_address, value, and timestamp.

[Assistant]
SELECT transaction_id, from_address, to_address, value, timestamp
FROM web3.transactions
WHERE value > (SELECT AVG(value) FROM web3.transactions);


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement. ##Table Structure
CREATE TABLE insurance.policies ( policy_id.text, customer_id.text, product_id.text, agent_id.text, policy_number.text, start_date.date, end_date.date, premium_amount.numeric, coverage_limit.numeric, deductible.numeric, status.text, issued_at.timestamp, cancellation_date.date, cancellation_reason.text )
##Table Structure
CREATE TABLE project_fundraising_record ( id.text, project_id.text, project_name.text, rounds_name.text, investment_value.numeric, investment_date.text, introduction.text, valuation.numeric )
##Table Structure
CREATE TABLE social_media.posts ( post_id character varying(64) NOT NULL, user_id character varying(64) NOT NULL, content text, media_url text, media_type character varying(20), created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, updated_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, visibility character varying(20) NOT NULL DEFAULT 'public', location_lat numeric(9,6), location_lon numeric(9,6), PRIMARY KEY (post_id) )
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.hashtags ( hashtag_id character varying(64) NOT NULL, tag_name character varying(100) NOT NULL UNIQUE, created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, PRIMARY KEY (hashtag_id) )
CREATE TABLE social_media.messages (
    message_id character varying(64) NOT NULL, -- unique identifier for the message
    conversation_id character varying(64) NOT NULL, -- identifier for the conversation thread (FK to conversations.conversation_id)
    sender_user_id character varying(64) NOT NULL, -- identifier of the sender (FK to users.user_id)
    content text, -- textual content of the message
    media_url text, -- URL to attached media (image/video)
    media_type character varying(20), -- type of media ('image', 'video', null)
    sent_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, -- timestamp when message was sent
    read_at timestamp, -- timestamp when message was read by recipient(s)
    PRIMARY KEY (message_id)
)
CREATE TABLE social_media.conversation_participants ( participant_id.text, conversation_id.text, user_id.text, joined_at.timestamp, last_read_at.timestamp )
##Table Structure
CREATE TABLE insurance.agents ( agent_id character varying(64) NOT NULL, first_name character varying(100) NOT NULL, last_name character varying(100) NOT NULL, agency_name character varying(150), license_number character varying(100) NOT NULL UNIQUE, license_state character varying(50) NOT NULL, contact_email character varying(128) UNIQUE, contact_phone character varying(30), hire_date date, termination_date date, status character varying(20) NOT NULL DEFAULT 'Active', commission_rate numeric(5, 4) NOT NULL DEFAULT 0.05, manager_id character varying(64), PRIMARY KEY (agent_id) )
##Table Structure
CREATE TABLE 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 )
##Table Structure
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) )
##Table Structure
CREATE TABLE web3.transactions ( transaction_id character varying(64) NOT NULL, from_address character varying(128) NOT NULL, to_address character varying(128), value numeric(38,14) NOT NULL, gas_used integer NOT NULL, gas_price numeric(38,14) NOT NULL, block_number integer NOT NULL, timestamp timestamp NOT NULL, input_data text, status character varying(32) NOT NULL, nonce integer NOT NULL, PRIMARY KEY (transaction_id) )
CREATE TABLE web3.token_transfers (
    transfer_id character varying(64) NOT NULL,  -- unique identifier for the transfer
    token_id character varying(64) NOT NULL, -- identifier of the token being transferred
    from_address character varying(128) NOT NULL, -- address of the sender
    to_address character varying(128) NOT NULL, -- address of the receiver
    value numeric(38,14) NOT NULL, -- amount of tokens transferred
    transaction_id character varying(64) NOT NULL, -- identifier of the transaction containing the transfer
    log_index integer NOT NULL, -- index of the transfer log in the transaction
    PRIMARY KEY (transfer_id)
)
##Table Structure
CREATE TABLE healthcare.medical_records ( record_id text PRIMARY KEY, patient_id text, appointment_id text, doctor_id text, record_date timestamp, chief_complaint text, present_illness_history text, past_medical_history text, physical_examination_notes text, assessment text, treatment_plan text, vitals text, created_at timestamp )

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

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

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

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

[User] Which projects raised funds in January 2022?

[Assistant] SELECT project_name, rounds_name, investment_value, investment_date FROM project_fundraising_record WHERE investment_date >= '2022-01-01' AND investment_date < '2022-02-01';

[User] Please also show their introductions.

[Assistant] SELECT project_name, rounds_name, investment_value, investment_date, introduction FROM project_fundraising_record WHERE investment_date >= '2022-01-01' AND investment_date < '2022-02-01';

[User] How many distinct users have sent messages in each conversation? Return conversation_id and user_count.

[Assistant]
SELECT conversation_id,
       COUNT(DISTINCT sender_user_id) AS user_count
FROM social_media.messages
GROUP BY conversation_id;

[User] Which agents, along with their managers' full names, are licensed in 'TX' and are currently active?

[Assistant]
SELECT a.agent_id, a.first_name AS agent_first_name, a.last_name AS agent_last_name, m.first_name AS manager_first_name, m.last_name AS manager_last_name
FROM insurance.agents a
LEFT JOIN insurance.agents m ON a.manager_id = m.agent_id
WHERE a.license_state = 'TX' AND a.status = 'Active';

[User] Show all room types that offer 'WiFi' in their amenities.

[Assistant] SELECT room_type_id, property_id, type_name, amenities FROM hospitality_technology.room_types WHERE amenities LIKE '%WiFi%';

[User] Only include those with a base rate below 100 and return the results sorted by base_rate ascending.

[Assistant] SELECT room_type_id, property_id, type_name, amenities, base_rate FROM hospitality_technology.room_types WHERE amenities LIKE '%WiFi%' AND base_rate < 100 ORDER BY base_rate ASC;

[User] Show all maintenance logs where the 'next_service_due_date' is before the current date, including the log ID, service date, service type, and the overdue next service date.

[Assistant] SELECT log_id, service_date, service_type, next_service_due_date FROM transportation.maintenance_logs WHERE next_service_due_date < CURRENT_DATE;

[User] Show the top 5 transactions with the highest number of token transfers, along with their Ethereum value. Include transaction_id, token_transfer_count, and ether_value.

[Assistant]
SELECT
  tt.transaction_id,
  COUNT(tt.transfer_id) AS token_transfer_count,
  t.value AS ether_value
FROM web3.token_transfers tt
JOIN web3.transactions t
  ON tt.transaction_id = t.transaction_id
GROUP BY
  tt.transaction_id,
  t.value
ORDER BY token_transfer_count DESC
LIMIT 5;

[User] Show me all medical records created before January 1, 2022.

[Assistant] SELECT * FROM healthcare.medical_records WHERE record_date < '2022-01-01';


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement. ##Table Structure
CREATE TABLE 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 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 )
##Table Structure
CREATE TABLE gaming_technology.achievements ( achievement_id.uuid, game_id.uuid, name.text, description.text, icon_url.text, points.integer, hidden.boolean )
##Table Structure
CREATE TABLE insurance.claim_documents (
    document_id character varying(64) NOT NULL, -- unique identifier for the document
    claim_id character varying(64) NOT NULL, -- identifier of the claim this document relates to (FK to claims)
    document_type character varying(50) NOT NULL, -- e.g., Police Report, Photo, Invoice, Medical Bill
    file_name character varying(255) NOT NULL, -- original name of the uploaded file
    file_path character varying(512) NOT NULL, -- storage path (e.g., S3 URL, network path)
    file_size_bytes integer, -- size of the file in bytes
    mime_type character varying(100), -- MIME type of the file (e.g., 'image/jpeg', 'application/pdf')
    uploaded_by character varying(64), -- identifier of the user/system who uploaded (FK to users/customers)
    uploaded_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, -- time of upload
    description text, -- optional description of the document
    PRIMARY KEY (document_id)
)
##Table Structure
CREATE TABLE transportation.vehicles ( vehicle_id text PRIMARY KEY, license_plate text, vin text, make text, model text, year int, type text, capacity int, fuel_type text, status text, depot_id text, acquisition_date date )
CREATE TABLE transportation.locations ( location_id text 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 )
CREATE TABLE transportation.maintenance_logs ( log_id.text, vehicle_id.text, service_date.date, odometer_reading.integer, service_type.text, description.text, cost.numeric, mechanic_name.text, next_service_due_date.date )
CREATE TABLE transportation.fuel_logs (
    fuel_log_id 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 social_media.user_settings ( setting_id text, user_id text, theme text, email_notifications_enabled boolean, push_notifications_enabled boolean, private_profile boolean, updated_at timestamp )
##Table Structure
CREATE TABLE insurance.customers ( customer_id text PRIMARY KEY, first_name text, last_name text, date_of_birth date, ssn_hash text, address_line1 text, address_line2 text, city text, state text, zip_code text, country text, phone_number text, email text, created_at timestamp, updated_at timestamp, status text )

[User] Show me the total hours worked and total amount billed for each case that has associated invoices, along with the case ID and invoice number.

[Assistant]
SELECT t.case_id, i.invoice_number, SUM(t.hours_spent) AS total_hours, SUM(t.hours_spent * t.billing_rate) AS total_billed_amount
FROM legal_services.time_entries t
JOIN legal_services.invoices i ON t.invoice_id = i.invoice_id
GROUP BY t.case_id, i.invoice_number;

[User] List pairs of overlapping reservations for the same room, including both reservation IDs, room_id, and each reservation's check-in and check-out dates.

[Assistant]
SELECT r1.reservation_id AS reservation_id_1,
       r2.reservation_id AS reservation_id_2,
       r1.room_id,
       r1.check_in_date AS check_in_1,
       r1.check_out_date AS check_out_1,
       r2.check_in_date AS check_in_2,
       r2.check_out_date AS check_out_2
FROM reservations r1
JOIN reservations r2
  ON r1.room_id = r2.room_id
 AND r1.reservation_id < r2.reservation_id
 AND r1.check_in_date < r2.check_out_date
 AND r2.check_in_date < r1.check_out_date;

[User] Which players have unlocked any achievement?

[Assistant] SELECT DISTINCT player_id FROM player_achievements;

[User] Show me the player ID and the total number of points they've accumulated from all unlocked achievements.

[Assistant] SELECT pa.player_id, SUM(a.points) AS total_points FROM player_achievements pa JOIN achievements a ON pa.achievement_id = a.achievement_id GROUP BY pa.player_id;

[User] Can you filter this to only include players whose total points exceed 1000?

[Assistant] SELECT pa.player_id, SUM(a.points) AS total_points FROM player_achievements pa JOIN achievements a ON pa.achievement_id = a.achievement_id GROUP BY pa.player_id HAVING SUM(a.points) > 1000;

[User] Find all documents that have a description and list their document ID, file name, and description.

[Assistant] SELECT document_id, file_name, description FROM insurance.claim_documents WHERE description IS NOT NULL AND description != '';

[User] Retrieve each vehicle's make and model along with the date and description of its latest maintenance service.

[Assistant]
SELECT v.vehicle_id,
       v.make,
       v.model,
       m.service_date,
       m.description
FROM transportation.vehicles v
JOIN (
  SELECT vehicle_id,
         MAX(service_date) AS max_date
  FROM transportation.maintenance_logs
  GROUP BY vehicle_id
) latest
  ON v.vehicle_id = latest.vehicle_id
JOIN transportation.maintenance_logs m
  ON m.vehicle_id = latest.vehicle_id
 AND m.service_date = latest.max_date;

[User] Can you show me all user IDs that have both email and push notifications disabled, along with whether their profile is set to private?

[Assistant] SELECT user_id, private_profile FROM social_media.user_settings WHERE email_notifications_enabled = false AND push_notifications_enabled = false;

[User] I also want to see the last time they updated their settings.

[Assistant] SELECT user_id, private_profile, updated_at FROM social_media.user_settings WHERE email_notifications_enabled = false AND push_notifications_enabled = false;

[User] List all addresses (address_line1, city, state) where more than one customer resides, and show how many customers share each address.

[Assistant]
SELECT address_line1,
       city,
       state,
       COUNT(*) AS resident_count
FROM insurance.customers
GROUP BY address_line1, city, state
HAVING COUNT(*) > 1;

[User] Include a comma-separated list of customer IDs for each of those addresses as customer_ids.

[Assistant]
SELECT address_line1,
       city,
       state,
       COUNT(*) AS resident_count,
       STRING_AGG(customer_id, ',') AS customer_ids
FROM insurance.customers
GROUP BY address_line1, city, state
HAVING COUNT(*) > 1;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement. ##Table Structure
CREATE TABLE social_media.follows ( follow_id.text, follower_user_id.text, following_user_id.text, created_at.timestamp )
CREATE TABLE social_media.conversation_participants ( participant_id.text, conversation_id.text, user_id.text, joined_at.timestamp, last_read_at.timestamp )
##Table Structure
CREATE TABLE healthcare.patients ( patient_id character varying(64) NOT NULL, first_name character varying(100) NOT NULL, last_name character varying(100) NOT NULL, date_of_birth date NOT NULL, gender character varying(10), address text, phone_number character varying(20), email character varying(128) UNIQUE, emergency_contact_name character varying(200), emergency_contact_phone character varying(20), created_at timestamp with time zone NOT NULL DEFAULT current_timestamp, updated_at timestamp with time zone NOT NULL DEFAULT current_timestamp, PRIMARY KEY (patient_id) )
CREATE TABLE healthcare.appointments ( appointment_id.text, patient_id.text, doctor_id.text, appointment_time.timestamp, duration_minutes.integer, reason.text, status.text, location_id.text, notes.text, created_at.timestamp )
CREATE TABLE healthcare.diagnoses (
    diagnosis_id character varying(64) NOT NULL, -- unique identifier for the diagnosis entry
    record_id character varying(64) NOT NULL, -- FK linking to the specific medical record entry
    patient_id character varying(64) NOT NULL, -- FK to patients table
    doctor_id character varying(64) NOT NULL, -- FK to doctors table (diagnosing doctor)
    diagnosis_code character varying(20) NOT NULL, -- standard code (e.g., ICD-10)
    code_type character varying(10) NOT NULL DEFAULT 'ICD-10', -- type of code used
    description text, -- textual description of the diagnosis
    diagnosis_date date NOT NULL, -- date the diagnosis was made
    status character varying(32) NOT NULL, -- e.g., Active, Resolved, Ruled Out
    is_chronic boolean DEFAULT false, -- flag for chronic conditions
    PRIMARY KEY (diagnosis_id)
)
CREATE TABLE healthcare.prescriptions ( prescription_id text, record_id text, patient_id text, doctor_id text, medication_id text, dosage text, frequency text, route text, start_date date, end_date date, quantity_dispensed numeric, refills_allowed integer, prescription_date timestamp )
CREATE TABLE healthcare.insurance_plans ( plan_id text, plan_name text, insurance_provider text, plan_type text, contact_phone text, website text )
CREATE TABLE healthcare.patient_insurance ( patient_insurance_id.text, patient_id.text, plan_id.text, policy_number.text, group_number.text, subscriber_name.text, effective_date.date, expiration_date.date, is_primary.boolean )
##Table Structure
CREATE TABLE transportation.trips ( trip_id text PRIMARY KEY, route_id text, vehicle_id text, driver_id text, scheduled_departure timestamp, actual_departure timestamp, scheduled_arrival timestamp, actual_arrival timestamp, origin_location_id text, destination_location_id text, status text, passenger_count int, cargo_manifest_id text )
CREATE TABLE transportation.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)
)
##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 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, 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 government_services.services ( service_id.text, agency_id.text, service_name.text, description.text, category.text, eligibility_criteria.text, standard_fee.numeric, average_processing_time_days.integer, is_active.boolean, online_application_url.text )
##Table Structure
CREATE TABLE government_services.documents ( document_id text, application_id text, citizen_id text, document_type text, file_reference text, upload_timestamp timestamp, expiry_date date, verification_status text, verified_by_employee_id text, verification_timestamp timestamp )

[User] For each user, count how many different conversations they have participated in. Show user_id and conversation_count.

[Assistant]
SELECT user_id, COUNT(DISTINCT conversation_id) AS conversation_count
FROM social_media.conversation_participants
GROUP BY user_id;

[User] List the full names and dates of birth for all patients who do not have a phone number on record.

[Assistant] SELECT first_name, last_name, date_of_birth FROM healthcare.patients WHERE phone_number IS NULL OR TRIM(phone_number) = '';

[User] Show a list of all trips along with the first and last names of all passengers who have booked on those trips. Each result should have the trip_id, passenger first name and last name.

[Assistant]
SELECT t.trip_id, p.first_name, p.last_name
FROM transportation.trips t
JOIN transportation.bookings b ON t.trip_id = b.trip_id
JOIN transportation.passengers p ON b.passenger_id = p.passenger_id;

[User] Provide the count of diagnoses by status.

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

[User] Now only include statuses with more than 10 diagnoses.

[Assistant]
SELECT status,
       COUNT(*) AS count
FROM healthcare.diagnoses
GROUP BY status
HAVING COUNT(*) > 10;

[User] Provide a list of all future appointments showing appointment_id, scheduled_start_time, location_name, city, and state.

[Assistant]
SELECT
  a.appointment_id,
  a.scheduled_start_time,
  sl.location_name,
  sl.city,
  sl.state
FROM appointments a
JOIN service_locations sl
  ON a.location_id = sl.location_id
WHERE a.scheduled_start_time > CURRENT_TIMESTAMP;

[User] Find pairs of active services from the same agency where one service's average processing time is longer than the other's. Display the agency_id, the slower service name with its processing time, and the faster service name with its processing time.

[Assistant]
SELECT
  s1.agency_id,
  s1.service_name AS slower_service_name,
  s1.average_processing_time_days AS slower_time,
  s2.service_name AS faster_service_name,
  s2.average_processing_time_days AS faster_time
FROM
  government_services.services s1
JOIN
  government_services.services s2
  ON s1.agency_id = s2.agency_id
  AND s1.average_processing_time_days > s2.average_processing_time_days
WHERE
  s1.is_active = true
  AND s2.is_active = true;

[User] List all document IDs and document types for documents that have been verified by an employee, along with the verification timestamp and the ID of the verifying employee.

[Assistant] SELECT document_id, document_type, verification_timestamp, verified_by_employee_id FROM government_services.documents WHERE verified_by_employee_id IS NOT NULL;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement. ##Table Structure
CREATE TABLE 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.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.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.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 )
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 transportation.drivers ( driver_id.text, employee_id.text, first_name.text, last_name.text, license_number.text, license_expiry_date.date, contact_number.text, email.text, hire_date.date, status.text )
CREATE TABLE transportation.routes ( route_id.text, route_number.text, description.text, origin_location_id.text, destination_location_id.text, distance_km.numeric, estimated_duration_minutes.integer, type.text )
CREATE TABLE transportation.trips ( trip_id.text, route_id.text, vehicle_id.text, driver_id.text, scheduled_departure.timestamp, actual_departure.timestamp, scheduled_arrival.timestamp, actual_arrival.timestamp, origin_location_id.text, destination_location_id.text, status.text, passenger_count.integer, cargo_manifest_id.text )
CREATE TABLE transportation.locations ( location_id.text, name.text, type.text, address_line1.text, city.text, state_province.text, postal_code.text, country.text, latitude.numeric, longitude.numeric, timezone.text )
CREATE TABLE transportation.maintenance_logs ( log_id.text, vehicle_id.text, service_date.date, odometer_reading.integer, service_type.text, description.text, cost.numeric, mechanic_name.text, next_service_due_date.date )
CREATE TABLE transportation.fuel_logs ( fuel_log_id.text, vehicle_id.text, trip_id.text, log_timestamp.timestamp, fuel_type.text, quantity.numeric, unit.text, cost_per_unit.numeric, total_cost.numeric, odometer_reading.integer, location_id.text )
CREATE TABLE transportation.passengers ( passenger_id.text, first_name.text, last_name.text, email.text, phone_number.text, date_of_birth.date, loyalty_program_id.text, created_at.timestamp )
CREATE TABLE transportation.bookings ( booking_id.text, passenger_id.text, trip_id.text, seat_number.text, booking_time.timestamp, status.text, fare.numeric, payment_transaction_id.text, special_requests.text )
##Table Structure
CREATE TABLE social_media.post_hashtags ( post_hashtag_id character varying(64) NOT NULL, post_id character varying(64) NOT NULL, hashtag_id character varying(64) NOT NULL, PRIMARY KEY (post_hashtag_id), CONSTRAINT unique_post_hashtag UNIQUE (post_id, hashtag_id) )
##Table Structure
CREATE TABLE web3.wallets ( wallet_id.text, user_id.text, address.text, private_key.text, created_at.timestamp )
##Table Structure
CREATE TABLE healthcare.patients ( patient_id.text, first_name.text, last_name.text, date_of_birth.date, gender.text, address.text, phone_number.text, email.text, emergency_contact_name.text, emergency_contact_phone.text, created_at.timestamp, updated_at.timestamp )
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 transportation.vehicles ( vehicle_id text, license_plate text, vin text, make text, model text, year integer, type text, capacity integer, fuel_type text, status text, depot_id text, acquisition_date date )
CREATE TABLE transportation.drivers ( driver_id text, employee_id text, first_name text, last_name text, license_number text, license_expiry_date date, contact_number text, email text, hire_date date, status text )
CREATE TABLE transportation.routes ( route_id text, route_number text, description text, origin_location_id text, destination_location_id text, distance_km numeric, estimated_duration_minutes integer, type text )
CREATE TABLE transportation.trips ( trip_id text, route_id text, vehicle_id text, driver_id text, scheduled_departure timestamp, actual_departure timestamp, scheduled_arrival timestamp, actual_arrival timestamp, origin_location_id text, destination_location_id text, status text, passenger_count integer, cargo_manifest_id text )
CREATE TABLE transportation.locations ( location_id text, name text, type text, address_line1 text, city text, state_province text, postal_code text, country text, latitude numeric, longitude numeric, timezone text )
CREATE TABLE transportation.maintenance_logs ( log_id text, vehicle_id text, service_date date, odometer_reading integer, service_type text, description text, cost numeric, mechanic_name text, next_service_due_date date )
CREATE TABLE transportation.fuel_logs ( fuel_log_id text, vehicle_id text, trip_id text, log_timestamp timestamp, fuel_type text, quantity numeric, unit text, cost_per_unit numeric, total_cost numeric, odometer_reading integer, location_id text )
CREATE TABLE transportation.passengers ( passenger_id text, first_name text, last_name text, email text, phone_number text, date_of_birth date, loyalty_program_id text, created_at timestamp )

[User] How many payments were made using the payment method 'Credit Card'?

[Assistant]
SELECT COUNT(*) AS credit_card_payments
FROM government_services.payments
WHERE payment_method = 'Credit Card';

[User] What was the total quantity and total cost of 'Gasoline' fuel logged in the year 2023?

[Assistant] SELECT SUM(quantity) ,  SUM(total_cost) FROM transportation.fuel_logs WHERE fuel_type  =  'Gasoline' AND EXTRACT(YEAR FROM log_timestamp)  =  2023

[User] List all distinct pairs of hashtag_id that are applied to the same post_id.

[Assistant]
SELECT ph1.post_id, ph1.hashtag_id AS hashtag1_id, ph2.hashtag_id AS hashtag2_id
FROM social_media.post_hashtags ph1
JOIN social_media.post_hashtags ph2
  ON ph1.post_id = ph2.post_id
  AND ph1.hashtag_id < ph2.hashtag_id;

[User] I also want to see the total number of posts where each hashtag pair co-occurs.

[Assistant]
SELECT ph1.hashtag_id AS hashtag1_id, ph2.hashtag_id AS hashtag2_id, COUNT(DISTINCT ph1.post_id) AS co_occurrence_count
FROM social_media.post_hashtags ph1
JOIN social_media.post_hashtags ph2
  ON ph1.post_id = ph2.post_id
  AND ph1.hashtag_id < ph2.hashtag_id
GROUP BY ph1.hashtag_id, ph2.hashtag_id;

[User] List all pairs of wallet addresses that were created by the same user but on different dates. Show both wallet IDs, their addresses, the user ID, and their creation dates.

[Assistant]
SELECT w1.wallet_id AS wallet_id_1, w1.address AS address_1, w2.wallet_id AS wallet_id_2, w2.address AS address_2, w1.user_id, DATE(w1.created_at) AS created_date_1, DATE(w2.created_at) AS created_date_2
FROM web3.wallets w1
JOIN web3.wallets w2 ON w1.user_id = w2.user_id AND w1.wallet_id < w2.wallet_id
WHERE DATE(w1.created_at) <> DATE(w2.created_at);

[User] Show each patient's first_name, last_name, and the time of their next scheduled appointment occurring after the current timestamp.

[Assistant]
SELECT p.first_name, p.last_name, MIN(a.appointment_time) AS next_appointment_time
FROM healthcare.patients p
JOIN healthcare.appointments a ON p.patient_id = a.patient_id
WHERE a.status = 'scheduled'
  AND a.appointment_time > CURRENT_TIMESTAMP
GROUP BY p.first_name, p.last_name;

[User] Show a list of all fuel refueling events for each trip, including the trip ID, fuel type, quantity, total cost, and the name of the refueling location.

[Assistant]
SELECT fl.trip_id, fl.fuel_type, fl.quantity, fl.total_cost, l.name AS location_name
FROM transportation.fuel_logs fl
JOIN transportation.locations l ON fl.location_id = l.location_id;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement. ##Table Structure
CREATE TABLE 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 web3.contracts ( contract_id character varying(64) NOT NULL, address character varying(128) NOT NULL, abi text NOT NULL, bytecode text NOT NULL, deployer_address character varying(128) NOT NULL, deployed_at timestamp NOT NULL, network_id character varying(64) NOT NULL, status character varying(32) NOT NULL, PRIMARY KEY (contract_id) )
##Table Structure
CREATE TABLE 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 )
##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 social_media.messages ( message_id character varying(64) NOT NULL, conversation_id character varying(64) NOT NULL, sender_user_id character varying(64) NOT NULL, content text, media_url text, media_type character varying(20), sent_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, read_at timestamp, PRIMARY KEY (message_id) )
CREATE TABLE social_media.conversation_participants ( participant_id character varying(64) NOT NULL, conversation_id character varying(64) NOT NULL, user_id character varying(64) NOT NULL, joined_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, last_read_at timestamp, PRIMARY KEY (participant_id), CONSTRAINT unique_user_conversation UNIQUE (conversation_id, user_id) )
##Table Structure
CREATE TABLE hospitality_technology.properties ( property_id.text, property_name.text, address_line1.text, address_line2.text, city.text, state_province.text, postal_code.text, country_code.text, phone_number.text, email_address.text, property_type.text, star_rating.numeric, timezone.text, manager_staff_id.text, created_at.timestamp, updated_at.timestamp )
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 )
##Table Structure
CREATE TABLE insurance.insurance_products ( product_id character varying(64) NOT NULL, product_name character varying(150) NOT NULL, product_type character varying(50) NOT NULL, description text, base_premium numeric(10, 2) NOT NULL, coverage_details text, underwriting_rules text, is_active boolean NOT NULL DEFAULT true, created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, updated_at timestamp, PRIMARY KEY (product_id) )

[User] Show each contract address and the count of successful transactions sent to that contract.

[Assistant] SELECT c.address, COUNT(t.transaction_id) AS success_tx_count FROM web3.contracts c JOIN web3.transactions t ON t.to_address = c.address AND t.status = 'success' GROUP BY c.address;

[User] Show all contracts that share the same deployment date, along with their contract IDs and the corresponding deployment date.

[Assistant]
SELECT a.contract_id AS contract_id_1, b.contract_id AS contract_id_2, a.deployed_at::date AS deployment_date
FROM web3.contracts a
JOIN web3.contracts b
  ON a.deployed_at::date = b.deployed_at::date AND a.contract_id < b.contract_id;

[User] Actually, I only want to see such pairs where the contracts were deployed by different deployer addresses.

[Assistant]
SELECT a.contract_id AS contract_id_1, b.contract_id AS contract_id_2, a.deployed_at::date AS deployment_date
FROM web3.contracts a
JOIN web3.contracts b
  ON a.deployed_at::date = b.deployed_at::date
  AND a.contract_id < b.contract_id
  AND a.deployer_address <> b.deployer_address;

[User] Show the total amount of payments processed by each payment_method.

[Assistant]
SELECT payment_method,
       SUM(amount) AS total_amount
FROM hospitality_technology.payments
GROUP BY payment_method;

[User] Include only payments with status 'Succeeded' or 'Pending', and order by total_amount descending.

[Assistant]
SELECT payment_method,
       SUM(amount) AS total_amount
FROM hospitality_technology.payments
WHERE status IN ('Succeeded', 'Pending')
GROUP BY payment_method
ORDER BY total_amount DESC;

[User] Find pairs of documents within the same case that were uploaded on the same day but by different lawyers. Show the case_id, upload_date, document_id and uploader_id for both documents in the pair.

[Assistant] SELECT d1.case_id, DATE(d1.upload_timestamp) AS upload_date, d1.document_id AS document1_id, d1.uploaded_by_lawyer_id AS lawyer1_id, d2.document_id AS document2_id, d2.uploaded_by_lawyer_id AS lawyer2_id FROM legal_services.documents AS d1 JOIN legal_services.documents AS d2 ON d1.case_id = d2.case_id AND DATE(d1.upload_timestamp) = DATE(d2.upload_timestamp) AND d1.uploaded_by_lawyer_id <> d2.uploaded_by_lawyer_id WHERE d1.document_id < d2.document_id;

[User] List `user_id` and `conversation_id` for participants who are in conversations where there is at least one message sent by *another* user that they have not read.

[Assistant] SELECT DISTINCT T1.user_id, T1.conversation_id FROM social_media.conversation_participants AS T1 JOIN social_media.messages AS T2 ON T1.conversation_id = T2.conversation_id WHERE T2.sender_user_id != T1.user_id AND (T1.last_read_at IS NULL OR T2.sent_at > T1.last_read_at);

[User] List each property along with the number of service orders placed by its manager in the last 30 days.

[Assistant]
SELECT p.property_name, COUNT(so.order_id) AS order_count
FROM hospitality_technology.properties p
JOIN hospitality_technology.service_orders so
  ON p.manager_staff_id = so.staff_id_ordered
WHERE so.order_timestamp >= NOW() - INTERVAL '30 days'
GROUP BY p.property_name;

[User] Show product_id, product_name, and base_premium for the five most recently created active insurance products.

[Assistant]
SELECT product_id, product_name, base_premium
FROM insurance.insurance_products
WHERE is_active = true
ORDER BY created_at DESC
LIMIT 5;