System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement. ##Table Structure
CREATE TABLE healthcare.doctors ( doctor_id character varying(64) NOT NULL, first_name character varying(100) NOT NULL, last_name character varying(100) NOT NULL, specialty character varying(100) NOT NULL, license_number character varying(50) UNIQUE NOT NULL, phone_number character varying(20), email character varying(128) UNIQUE, hospital_affiliation_id character varying(64), created_at timestamp with time zone NOT NULL DEFAULT current_timestamp, updated_at timestamp with time zone NOT NULL DEFAULT current_timestamp, PRIMARY KEY (doctor_id) )
CREATE TABLE healthcare.prescriptions ( prescription_id character varying(64) NOT NULL, record_id character varying(64) NOT NULL, patient_id character varying(64) NOT NULL, doctor_id character varying(64) NOT NULL, medication_id character varying(64) NOT NULL, dosage character varying(100) NOT NULL, frequency character varying(100) NOT NULL, route character varying(50), start_date date NOT NULL, end_date date, quantity_dispensed numeric(10,2), refills_allowed integer NOT NULL DEFAULT 0, prescription_date timestamp with time zone NOT NULL DEFAULT current_timestamp, PRIMARY KEY (prescription_id) )
##Table Structure
CREATE TABLE web3.token_transfers ( transfer_id text PRIMARY KEY, token_id text, from_address text, to_address text, value numeric, transaction_id text, log_index int )
##Table Structure
CREATE TABLE 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 government_services.citizens ( citizen_id character varying(64) NOT NULL, national_id_number character varying(128) NOT NULL UNIQUE, first_name character varying(100) NOT NULL, last_name character varying(100) NOT NULL, date_of_birth date NOT NULL, gender character varying(20), primary_address text NOT NULL, contact_email character varying(128) UNIQUE, contact_phone character varying(32), registration_date timestamp NOT NULL, is_verified boolean DEFAULT false, PRIMARY KEY (citizen_id) )
CREATE TABLE government_services.applications ( application_id text, citizen_id text, service_id text, submitted_at timestamp, status text, last_updated_at timestamp, assigned_employee_id text, decision_date date, notes text, reference_number text )
##Table Structure
CREATE TABLE 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) )
##Table Structure
CREATE TABLE web3.users ( user_id character varying(64) NOT NULL, username character varying(128) NOT NULL, email character varying(128) NOT NULL, password_hash text NOT NULL, created_at timestamp NOT NULL, PRIMARY KEY (user_id) )
##Table Structure
CREATE TABLE gaming_technology.player_achievements ( player_achievement_id.uuid, player_id.uuid, achievement_id.uuid, unlocked_at.timestamptz )
##Table Structure
CREATE TABLE legal_services.appointments ( appointment_id text PRIMARY KEY, client_id text, lawyer_id text, case_id text, start_time timestamp, end_time timestamp, location text, subject text, notes text, status text, created_at timestamp )
##Table Structure
CREATE TABLE social_media.hashtags ( hashtag_id.text, tag_name.text, created_at.timestamp )
CREATE TABLE social_media.conversations ( conversation_id.text, created_at.timestamp, last_message_at.timestamp, is_group_chat.boolean, group_name.text )

[User] How many prescriptions are there for each refills_allowed value?

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

[User] Find all addresses that have only sent tokens (appear in from_address) but have never received any (do not appear in to_address).

[Assistant] SELECT DISTINCT from_address FROM web3.token_transfers WHERE from_address NOT IN (SELECT DISTINCT to_address FROM web3.token_transfers);

[User] For these addresses that have only sent tokens, show the total value of tokens each has sent.

[Assistant] SELECT t1.from_address, SUM(t1.value) AS total_sent_value FROM web3.token_transfers AS t1 WHERE t1.from_address NOT IN (SELECT DISTINCT to_address FROM web3.token_transfers) GROUP BY t1.from_address;

[User] Show the total payment amount and the number of payments processed by each staff member, including their staff_id_processed.

[Assistant] SELECT staff_id_processed, SUM(amount) AS total_payment_amount, COUNT(payment_id) AS payment_count FROM hospitality_technology.payments GROUP BY staff_id_processed;

[User] Find, for each case, pairs of documents where one document_type is 'Contract' and the other is 'Evidence'. Return the case_id, the name of the contract document as contract_name, and the name of the evidence document as evidence_name.

[Assistant]
SELECT d1.case_id,
       d1.document_name AS contract_name,
       d2.document_name AS evidence_name
FROM legal_services.documents d1
JOIN legal_services.documents d2
  ON d1.case_id = d2.case_id
WHERE d1.document_type = 'Contract'
  AND d2.document_type = 'Evidence';

[User] List all citizens who submitted an application within 24 hours of registering. Show the application_id, citizen's full name, registration_date, and submitted_at timestamp.

[Assistant]
SELECT
a.application_id,
(c.first_name || ' ' || c.last_name) AS full_name,
c.registration_date,
a.submitted_at
FROM government_services.applications a
JOIN government_services.citizens c
  ON a.citizen_id = c.citizen_id
WHERE a.submitted_at <= c.registration_date + INTERVAL '24 hours';

[User] How many insurance products are currently marked as inactive?

[Assistant] SELECT count(*) FROM insurance.insurance_products WHERE is_active = false;

[User] List all pairs of users who share the same email domain, showing each pair’s user_id, username, and the common domain.

[Assistant]
SELECT u1.user_id AS user1_id,
       u1.username AS user1_name,
       u2.user_id AS user2_id,
       u2.username AS user2_name,
       split_part(u1.email, '@', 2) AS domain
FROM web3.users u1
JOIN web3.users u2
  ON split_part(u1.email, '@', 2) = split_part(u2.email, '@', 2)
 AND u1.user_id < u2.user_id;

[User] Show me all players who have unlocked achievements, and for each, also list the total number of achievements they've unlocked.

[Assistant] SELECT player_id, COUNT(*) AS achievements_unlocked FROM gaming_technology.player_achievements GROUP BY player_id;

[User] Now limit it to only players who have unlocked more than 5 achievements.

[Assistant] SELECT player_id, COUNT(*) AS achievements_unlocked FROM gaming_technology.player_achievements GROUP BY player_id HAVING COUNT(*) > 5;

[User] List each appointment along with the start_time of the next appointment for the same lawyer. Include appointment_id and next_start_time.

[Assistant]
SELECT appointment_id,
       LEAD(start_time) OVER (PARTITION BY lawyer_id ORDER BY start_time) AS next_start_time
FROM legal_services.appointments;

[User] Only include those where next_start_time is within 30 days of the original appointment.

[Assistant]
WITH ordered AS (
  SELECT appointment_id,
         start_time,
         LEAD(start_time) OVER (PARTITION BY lawyer_id ORDER BY start_time) AS next_start_time
  FROM legal_services.appointments
)
SELECT appointment_id, next_start_time
FROM ordered
WHERE next_start_time IS NOT NULL
  AND next_start_time <= start_time + INTERVAL '30 days';

[User] List conversation IDs and their creation times for all conversations that have not had any new messages in 2024.

[Assistant]
SELECT conversation_id, created_at
FROM social_media.conversations
WHERE last_message_at < '2024-01-01' OR last_message_at IS NULL;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement. ##Table Structure
CREATE TABLE web3.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 transportation.locations ( location_id text PRIMARY KEY, name text, type text, address_line1 text, city text, state_province text, postal_code text, country text, latitude numeric, longitude numeric, timezone text )
##Table Structure
CREATE TABLE transportation.routes ( route_id.text, route_number.text, description.text, origin_location_id.text, destination_location_id.text, distance_km.numeric, estimated_duration_minutes.integer, type.text )
CREATE TABLE transportation.maintenance_logs ( log_id.text, 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.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 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 smart_money_token_performance ( token_address character varying(100) NOT NULL, -- the token's address token_symbol character varying(100), -- the tokens's symbol pnl numeric(38,2), -- the profit users made on this token net_flow numeric(38,2), -- the netflow of the token, means the money user spent minus the the money user sold of this token avg_cost numeric(38,16), -- the average cost price of user spent on this token price double precision, -- the current price of the token realized_ratio numeric(10,2), -- the ratio user sold of the token roi numeric(10,2), -- the roi users made of this token chain character varying(100), -- the chain that the token resides PRIMARY KEY (token_address, chain) )
##Table Structure
CREATE TABLE insurance.customers ( customer_id.text, first_name.text, last_name.text, date_of_birth.date, ssn_hash.text, address_line1.text, address_line2.text, city.text, state.text, zip_code.text, country.text, phone_number.text, email.text, created_at.timestamp, updated_at.timestamp, status.text )
##Table Structure
CREATE TABLE smart_money_profit ( address text, rank numeric, profit numeric, roi numeric, realized_ratio numeric, most_profit_token text, last_trade_time text, chain text )
##Table Structure
CREATE TABLE 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 trading_platform.logs ( log_id character varying(64) NOT NULL, user_id character varying(64), action character varying(128) NOT NULL, details text NOT NULL, logged_at timestamp NOT NULL, PRIMARY KEY (log_id) )
##Table Structure
CREATE TABLE transportation.drivers ( driver_id.text, employee_id.text, first_name.text, last_name.text, license_number.text, license_expiry_date.date, contact_number.text, email.text, hire_date.date, status.text )
##Table Structure
CREATE TABLE insurance.claim_documents ( document_id.text, claim_id.text, document_type.text, file_name.text, file_path.text, file_size_bytes.integer, mime_type.text, uploaded_by.text, uploaded_at.timestamp, description.text )
##Table Structure
CREATE TABLE trading_platform.orders ( order_id.text, user_id.text, wallet_id.text, asset_id.text, order_type.text, quantity.numeric, price.numeric, status.text, created_at.timestamp )

[User] Find all wallets that were created by users with IDs starting with 'user_' and show their addresses along with creation timestamps.

[Assistant] SELECT address, created_at FROM web3.wallets WHERE user_id LIKE 'user_%';

[User] List all pairs of locations where both are located in the same timezone but are in different cities. Include both location IDs, names, the timezone, and their respective cities.

[Assistant]
SELECT l1.location_id AS location1_id, l1.name AS location1_name, l2.location_id AS location2_id, l2.name AS location2_name, l1.timezone, l1.city AS city1, l2.city AS city2
FROM transportation.locations l1
JOIN transportation.locations l2 ON l1.timezone = l2.timezone
    AND l1.city <> l2.city
    AND l1.location_id < l2.location_id;

[User] Retrieve the first_name, last_name, and email of all passengers who have never made a booking.

[Assistant]
SELECT
  p.first_name,
  p.last_name,
  p.email
FROM transportation.passengers p
LEFT JOIN transportation.bookings b
  ON p.passenger_id = b.passenger_id
WHERE b.booking_id IS NULL;

[User] Which services charge more than the average standard fee of their category? Show the service name, its fee, and the average fee for that category.

[Assistant]
SELECT
  s.service_name,
  s.standard_fee,
  avg_fees.avg_fee
FROM government_services.services s
JOIN (
  SELECT
    category,
    AVG(standard_fee) AS avg_fee
  FROM government_services.services
  GROUP BY category
) avg_fees
  ON s.category = avg_fees.category
WHERE s.standard_fee > avg_fees.avg_fee;

[User] What is the average ROI for tokens with a realized ratio above 50% across all chains?

[Assistant] SELECT AVG(roi) AS average_roi FROM smart_money_token_performance WHERE realized_ratio > 50;

[User] List the first name, last name, and email of all customers who live in New York or California.

[Assistant] SELECT first_name, last_name, email FROM insurance.customers WHERE state IN ('NY', 'CA');

[User] How many addresses on the Polygon chain have an ROI above 5?

[Assistant] SELECT COUNT(*) AS address_count FROM smart_money_profit WHERE chain = 'Polygon' AND roi > 5;

[User] Also show the average profit of these addresses.

[Assistant] SELECT COUNT(*) AS address_count, AVG(profit) AS avg_profit FROM smart_money_profit WHERE chain = 'Polygon' AND roi > 5;

[User] List pairs of distinct routes that originate from the same location but go to different destinations. Show the route ID and route number for both routes and the common 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 AS shared_origin_location_id
FROM transportation.routes AS r1
JOIN transportation.routes AS r2
  ON r1.origin_location_id = r2.origin_location_id
  AND r1.route_id < r2.route_id
WHERE
  r1.destination_location_id != r2.destination_location_id;

[User] Show the earliest and latest timestamp recorded in the logs table.

[Assistant] SELECT MIN(logged_at), MAX(logged_at) FROM trading_platform.logs;

[User] Find all pairs of drivers who have the same license expiry date. For each pair, provide both driver_ids, full names, and the shared expiry date.

[Assistant]
SELECT d1.driver_id AS driver1_id, d1.first_name || ' ' || d1.last_name AS driver1_name,
       d2.driver_id AS driver2_id, d2.first_name || ' ' || d2.last_name AS driver2_name,
       d1.license_expiry_date
FROM transportation.drivers d1
JOIN transportation.drivers d2
  ON d1.license_expiry_date = d2.license_expiry_date
 AND d1.driver_id < d2.driver_id;

[User] How many distinct users have uploaded claim documents of type 'ACCIDENT_REPORT'?

[Assistant] SELECT COUNT(DISTINCT uploaded_by) FROM insurance.claim_documents WHERE document_type = 'ACCIDENT_REPORT';

[User] Count the number of orders in each status.

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


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement. ##Table Structure
CREATE TABLE insurance.insurance_products (
    product_id character varying(64) NOT NULL, -- unique identifier for the insurance product
    product_name character varying(150) NOT NULL, -- name of the insurance product (e.g., 'Comprehensive Auto Insurance')
    product_type character varying(50) NOT NULL, -- category like 'Auto', 'Home', 'Life', 'Health', 'Travel'
    description text, -- detailed description of the product
    base_premium numeric(10, 2) NOT NULL, -- starting premium before adjustments
    coverage_details text, -- details about what is covered (could be JSON or structured text)
    underwriting_rules text, -- rules used for assessing risk and eligibility
    is_active boolean NOT NULL DEFAULT true, -- whether the product is currently offered
    created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
    updated_at timestamp,
    PRIMARY KEY (product_id)
)
##Table Structure
CREATE TABLE legal_services.law_firms ( firm_id.text, firm_name.text, address.text, phone.text, website.text, founded_date.date, managing_partner_id.text )
##Table Structure
CREATE TABLE insurance.customers ( customer_id.text, first_name.text, last_name.text, date_of_birth.date, ssn_hash.text, address_line1.text, address_line2.text, city.text, state.text, zip_code.text, country.text, phone_number.text, email.text, created_at.timestamp, updated_at.timestamp, status.text )
CREATE TABLE insurance.claims ( claim_id text, policy_id text, customer_id text, incident_date timestamp, reported_date timestamp, description text, estimated_loss numeric, status text, settlement_amount numeric, settlement_date date, claim_handler_id text, police_report_number text )
##Table Structure
CREATE TABLE transportation.locations ( location_id text PRIMARY KEY, name text, type text, address_line1 text, city text, state_province text, postal_code text, country text, latitude numeric, longitude numeric, timezone text )
##Table Structure
CREATE TABLE social_media.users ( user_id.text, username.text, email.text, password_hash.text, full_name.text, profile_picture_url.text, bio.text, location.text, created_at.timestamp, updated_at.timestamp, is_verified.boolean )
CREATE TABLE social_media.posts ( post_id.text, user_id.text, content.text, media_url.text, media_type.text, created_at.timestamp, updated_at.timestamp, visibility.text, location_lat.numeric, location_lon.numeric )
CREATE TABLE social_media.comments ( comment_id.text, post_id.text, user_id.text, parent_comment_id.text, content.text, created_at.timestamp, updated_at.timestamp )
CREATE TABLE social_media.likes ( like_id.text, user_id.text, post_id.text, comment_id.text, created_at.timestamp )
CREATE TABLE social_media.follows ( follow_id.text, follower_user_id.text, following_user_id.text, created_at.timestamp )
CREATE TABLE social_media.conversation_participants ( participant_id.text, conversation_id.text, user_id.text, joined_at.timestamp, last_read_at.timestamp )
##Table Structure
CREATE TABLE insurance.claims (
    claim_id character varying(64) NOT NULL, -- unique identifier for the claim
    policy_id character varying(64) NOT NULL, -- identifier of the policy under which the claim is made (FK to policies)
    customer_id character varying(64) NOT NULL, -- identifier of the customer making the claim (FK to customers)
    incident_date timestamp NOT NULL, -- date and time of the incident leading to the claim
    reported_date timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, -- date the claim was reported
    description text NOT NULL, -- detailed description of the incident and claim
    estimated_loss numeric(15, 2), -- initial estimated cost of the loss
    status character varying(30) NOT NULL, -- e.g., Filed, Processing, Under Review, Approved, Denied, Settled
    settlement_amount numeric(15, 2), -- final amount paid out
    settlement_date date,
    claim_handler_id character varying(64), -- identifier for the employee handling the claim (FK to employees/adjusters)
    police_report_number character varying(100),
    PRIMARY KEY (claim_id)
)
##Table Structure
CREATE TABLE government_services.citizens ( citizen_id text PRIMARY KEY, national_id_number text, first_name text, last_name text, date_of_birth date, gender text, primary_address text, contact_email text, contact_phone text, registration_date timestamp, is_verified boolean )
CREATE TABLE government_services.notifications ( notification_id text PRIMARY KEY, citizen_id text, application_id text, message_subject text, message_body text, channel text, sent_at timestamp, status text, related_entity_type text, related_entity_id text )
##Table Structure
CREATE TABLE healthcare.diagnoses ( diagnosis_id.text, record_id.text, patient_id.text, doctor_id.text, diagnosis_code.text, code_type.text, description.text, diagnosis_date.date, status.text, is_chronic.boolean )
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 )
##Table Structure
CREATE TABLE healthcare.doctors ( doctor_id text, first_name text, last_name text, specialty text, license_number text, phone_number text, email text, hospital_affiliation_id text, created_at timestamp, updated_at timestamp )
CREATE TABLE healthcare.insurance_plans ( plan_id text, plan_name text, insurance_provider text, plan_type text, contact_phone text, website text )

[User] Retrieve the product_id, product_name, base_premium, and created_at for all active insurance products with a base_premium greater than 1000, ordered by base_premium descending.

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

[User] Find all pairs of law firms founded in the same year, showing both firm names and the shared founding year.

[Assistant]
SELECT f1.firm_name AS firm1, f2.firm_name AS firm2, EXTRACT(YEAR FROM f1.founded_date) AS founding_year
FROM legal_services.law_firms f1
JOIN legal_services.law_firms f2
  ON EXTRACT(YEAR FROM f1.founded_date) = EXTRACT(YEAR FROM f2.founded_date)
  AND f1.firm_id < f2.firm_id;

[User] How many unique customers are there in the system?

[Assistant]
SELECT COUNT(DISTINCT customer_id) AS unique_customer_count
FROM insurance.customers;

[User] Find all distinct pairs of locations that are located in the same city. List their IDs, names, and the shared city.

[Assistant] SELECT l1.location_id AS location1_id, l1.name AS location1_name, l2.location_id AS location2_id, l2.name AS location2_name, l1.city FROM transportation.locations AS l1 JOIN transportation.locations AS l2 ON l1.city = l2.city AND l1.location_id < l2.location_id;

[User] Show the usernames and their profile picture URLs for users who have a profile picture set and are also verified.

[Assistant] SELECT username, profile_picture_url FROM social_media.users WHERE profile_picture_url IS NOT NULL AND profile_picture_url != '' AND is_verified = TRUE;

[User] Calculate the average number of days between when an incident occurred and when the claim was reported, but only for claims that were settled in the year 2023.

[Assistant]
SELECT
  AVG(EXTRACT(EPOCH FROM (reported_date - incident_date)) / 86400.0)::numeric(10, 2)
FROM
  insurance.claims
WHERE
  settlement_date IS NOT NULL AND EXTRACT(YEAR FROM settlement_date) = 2023;

[User] List the first_name, last_name, and registration_date of citizens who registered in 2023 but are still not verified.

[Assistant]
SELECT first_name,
       last_name,
       registration_date
FROM government_services.citizens
WHERE registration_date >= '2023-01-01'
  AND registration_date <  '2024-01-01'
  AND is_verified = FALSE;

[User] For each diagnosis code_type, calculate the average number of refills_allowed for prescriptions linked to chronic diagnoses.

[Assistant]
SELECT
  d.code_type,
  AVG(p.refills_allowed) AS avg_refills_allowed
FROM healthcare.diagnoses d
JOIN healthcare.prescriptions p
  ON d.record_id = p.record_id
WHERE d.is_chronic = TRUE
GROUP BY d.code_type;

[User] List the names and contact phone numbers of all insurance plans whose website is not null.

[Assistant]
SELECT plan_name, contact_phone
FROM healthcare.insurance_plans
WHERE website 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 healthcare.medical_records ( record_id character varying(64) NOT NULL, patient_id character varying(64) NOT NULL, appointment_id character varying(64) UNIQUE, doctor_id character varying(64) NOT NULL, record_date timestamp with time zone NOT NULL, chief_complaint text, present_illness_history text, past_medical_history text, physical_examination_notes text, assessment text, treatment_plan text, vitals jsonb, created_at timestamp with time zone NOT NULL DEFAULT current_timestamp, PRIMARY KEY (record_id) )
CREATE TABLE healthcare.prescriptions ( prescription_id character varying(64) NOT NULL, record_id character varying(64) NOT NULL, patient_id character varying(64) NOT NULL, doctor_id character varying(64) NOT NULL, medication_id character varying(64) NOT NULL, dosage character varying(100) NOT NULL, frequency character varying(100) NOT NULL, route character varying(50), start_date date NOT NULL, end_date date, quantity_dispensed numeric(10,2), refills_allowed integer NOT NULL DEFAULT 0, prescription_date timestamp with time zone NOT NULL DEFAULT current_timestamp, PRIMARY KEY (prescription_id) )
##Table Structure
CREATE TABLE hospitality_technology.reviews ( review_id text PRIMARY KEY, property_id text, reservation_id text, guest_id text, rating_overall int, rating_cleanliness int, rating_service int, rating_location int, rating_value int, 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 government_services.employees ( employee_id text, agency_id text, first_name text, last_name text, job_title text, department text, work_email text, work_phone text, hire_date date, termination_date date, access_level text, manager_employee_id text )
##Table Structure
CREATE TABLE trading_platform.kyc_audit ( kyc_audit_id.text, user_id.text, status.text, reviewed_at.timestamp )
##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.utxos ( utxo_id.text, transaction_id.text, output_index.integer, address.text, amount.numeric, spent.boolean )
##Table Structure
CREATE TABLE blockchain.nodes ( node_id text PRIMARY KEY, ip_address text, port int, last_seen timestamp )
##Table Structure
CREATE TABLE smart_money_profit ( address text, rank numeric, profit numeric, roi numeric, realized_ratio numeric, most_profit_token text, last_trade_time text, chain text )
##Table Structure
CREATE TABLE web3.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.transactions ( transaction_id text, from_address text, to_address text, value numeric, gas_used integer, gas_price numeric, block_number integer, timestamp timestamp, input_data text, status text, nonce integer )
CREATE TABLE web3.tokens ( token_id text, contract_address text, token_name text, token_symbol text, decimals integer, total_supply numeric )
CREATE TABLE web3.token_transfers ( transfer_id text, token_id text, from_address text, to_address text, value numeric, transaction_id text, log_index integer )
CREATE TABLE web3.users ( user_id text, username text, email text, password_hash text, created_at timestamp )
##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, follower_user_id.text, following_user_id.text, created_at.timestamp )
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.conversations ( conversation_id text PRIMARY KEY, created_at timestamp, last_message_at timestamp, is_group_chat bool, group_name text )
CREATE TABLE social_media.user_settings ( setting_id text PRIMARY KEY, user_id text, theme text, email_notifications_enabled bool, push_notifications_enabled bool, private_profile bool, updated_at timestamp )

[User] For each patient, count the total number of medical records they have in the system, and show patient_id along with record_count.

[Assistant]
SELECT patient_id,
       COUNT(*) AS record_count
FROM healthcare.medical_records
GROUP BY patient_id;

[User] For each overall rating level (1-5), count how many reviews received that rating.

[Assistant] SELECT rating_overall, COUNT(*) FROM reviews GROUP BY rating_overall ORDER BY rating_overall;

[User] Only show ratings with more than 100 reviews and sort by the count descending.

[Assistant] SELECT rating_overall, COUNT(*) FROM reviews GROUP BY rating_overall HAVING COUNT(*) > 100 ORDER BY COUNT(*) DESC;

[User] List the full names of employees whose direct manager themselves report to another manager. Also show the direct manager's full name.

[Assistant] SELECT E.first_name, E.last_name, M.first_name AS manager_first_name, M.last_name AS manager_last_name FROM government_services.employees AS E JOIN government_services.employees AS M ON E.manager_employee_id = M.employee_id WHERE M.manager_employee_id IS NOT NULL;

[User] Show me all users who had their KYC rejected along with when their review was completed.

[Assistant] SELECT user_id, reviewed_at FROM trading_platform.kyc_audit WHERE status = 'rejected';

[User] List public reviews whose comment contains the word 'slow'.

[Assistant] SELECT review_id, comment, review_date, rating_overall, property_id FROM hospitality_technology.reviews WHERE is_public = TRUE AND LOWER(comment) LIKE '%slow%';

[User] Also, only include reviews submitted for property 'P007'.

[Assistant] SELECT review_id, comment, review_date, rating_overall, property_id FROM hospitality_technology.reviews WHERE is_public = TRUE AND LOWER(comment) LIKE '%slow%' AND property_id = 'P007';

[User] Show me the distribution of UTXO amounts by creating buckets (0-10, 10-50, 50-100, 100-500, 500+), along with the count and total amount in each bucket.

[Assistant] SELECT CASE WHEN amount <= 10 THEN '0-10' WHEN amount <= 50 THEN '10-50' WHEN amount <= 100 THEN '50-100' WHEN amount <= 500 THEN '100-500' ELSE '500+' END AS amount_range, COUNT(*) AS utxo_count, SUM(amount) AS total_amount FROM trading_platform.utxos GROUP BY amount_range ORDER BY MIN(amount);

[User] Show me pairs of node_id and node_id for nodes that share the same ip_address but have different port numbers.

[Assistant] SELECT n1.node_id AS node_id1, n2.node_id AS node_id2, n1.ip_address, n1.port AS port1, n2.port AS port2 FROM blockchain.nodes n1 JOIN blockchain.nodes n2 ON n1.ip_address = n2.ip_address WHERE n1.node_id < n2.node_id AND n1.port <> n2.port;

[User] What is the average profit and average ROI for smart money addresses ranked in the top 500?

[Assistant] SELECT AVG(profit), AVG(roi) FROM smart_money_profit WHERE rank <= 500

[User] For each contract, can you list the token symbols and total supply of all tokens created by that contract, along with the contract's current status?

[Assistant]
SELECT c.contract_id, c.address AS contract_address, c.status, t.token_symbol, t.total_supply
FROM web3.contracts c
JOIN web3.tokens t ON c.address = t.contract_address
ORDER BY c.contract_id, t.token_symbol;

[User] How many followers does each user have? Show user_id and follower_count.

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


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement. ##Table Structure
CREATE TABLE insurance.customers ( customer_id text, first_name text, last_name text, date_of_birth date, ssn_hash text, address_line1 text, address_line2 text, city text, state text, zip_code text, country text, phone_number text, email text, created_at timestamp, updated_at timestamp, status text )
CREATE TABLE insurance.claims (
    claim_id character varying(64) NOT NULL, -- unique identifier for the claim
    policy_id character varying(64) NOT NULL, -- identifier of the policy under which the claim is made (FK to policies)
    customer_id character varying(64) NOT NULL, -- identifier of the customer making the claim (FK to customers)
    incident_date timestamp NOT NULL, -- date and time of the incident leading to the claim
    reported_date timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, -- date the claim was reported
    description text NOT NULL, -- detailed description of the incident and claim
    estimated_loss numeric(15, 2), -- initial estimated cost of the loss
    status character varying(30) NOT NULL, -- e.g., Filed, Processing, Under Review, Approved, Denied, Settled
    settlement_amount numeric(15, 2), -- final amount paid out
    settlement_date date,
    claim_handler_id character varying(64), -- identifier for the employee handling the claim (FK to employees/adjusters)
    police_report_number character varying(100),
    PRIMARY KEY (claim_id)
)
CREATE TABLE insurance.insurance_products (
    product_id character varying(64) NOT NULL, -- unique identifier for the insurance product
    product_name character varying(150) NOT NULL, -- name of the insurance product (e.g., 'Comprehensive Auto Insurance')
    product_type character varying(50) NOT NULL, -- category like 'Auto', 'Home', 'Life', 'Health', 'Travel'
    description text, -- detailed description of the product
    base_premium numeric(10, 2) NOT NULL, -- starting premium before adjustments
    coverage_details text, -- details about what is covered (could be JSON or structured text)
    underwriting_rules text, -- rules used for assessing risk and eligibility
    is_active boolean NOT NULL DEFAULT true, -- whether the product is currently offered
    created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
    updated_at timestamp,
    PRIMARY KEY (product_id)
)
CREATE TABLE insurance.claim_documents ( document_id character varying(64) NOT NULL, claim_id character varying(64) NOT NULL, document_type character varying(50) NOT NULL, file_name character varying(255) NOT NULL, file_path character varying(512) NOT NULL, file_size_bytes integer, mime_type character varying(100), uploaded_by character varying(64), uploaded_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, description text, PRIMARY KEY (document_id) )
##Table Structure
CREATE TABLE blockchain.wallets ( wallet_id.text, user_id.text, address_id.text, private_key.text )
CREATE TABLE blockchain.users ( user_id.text, username.text, email.text, password_hash.text )
##Table Structure
CREATE TABLE 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 )
##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 insurance.premium_payments ( payment_id character varying(64) NOT NULL, policy_id character varying(64) NOT NULL, customer_id character varying(64) NOT NULL, payment_date timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, amount_paid numeric(12, 2) NOT NULL, payment_method character varying(50), transaction_reference character varying(128) UNIQUE, due_date date, payment_period_start date, payment_period_end date, status character varying(30) NOT NULL DEFAULT 'Completed', PRIMARY KEY (payment_id) )
##Table Structure
CREATE TABLE web3.events ( event_id character varying(64) NOT NULL, contract_id character varying(64) NOT NULL, event_name character varying(128) NOT NULL, data text NOT NULL, emitted_at timestamp NOT NULL, transaction_id character varying(64) NOT NULL, log_index integer NOT NULL, PRIMARY KEY (event_id) )
##Table Structure
CREATE TABLE government_services.notifications ( notification_id text, citizen_id text, application_id text, message_subject text, message_body text, channel text, sent_at timestamp, status text, related_entity_type text, related_entity_id text )
##Table Structure
CREATE TABLE government_services.documents ( document_id text, application_id text, citizen_id text, document_type text, file_reference text, upload_timestamp timestamp, expiry_date date, verification_status text, verified_by_employee_id text, verification_timestamp timestamp )

[User] Show the total number of customers in each state.

[Assistant]
SELECT
  state,
  COUNT(customer_id)
FROM insurance.customers
GROUP BY
  state;

[User] List all users whose password hash contains the substring 'abc'.

[Assistant] SELECT user_id, username, password_hash FROM blockchain.users WHERE password_hash LIKE '%abc%';

[User] Also include their email address.

[Assistant] SELECT user_id, username, password_hash, email FROM blockchain.users WHERE password_hash LIKE '%abc%';

[User] Filter to only show users whose username does *not* contain 'test'.

[Assistant] SELECT user_id, username, password_hash, email FROM blockchain.users WHERE password_hash LIKE '%abc%' AND username NOT LIKE '%test%';

[User] Show a list of all DApps together with the total number of unique assets linked to each via the metadata table.

[Assistant]
SELECT d.dapp_id, d.name, d.url, COUNT(DISTINCT m.asset_id) AS unique_asset_count
FROM trading_platform.dapps d
LEFT JOIN trading_platform.metadata m ON m.asset_id IS NOT NULL
GROUP BY d.dapp_id, d.name, d.url;

[User] Find all pairs of different routes where the estimated duration in minutes is identical. For each pair, show both route IDs, their route numbers, and the shared duration.

[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.estimated_duration_minutes FROM transportation.routes r1 JOIN transportation.routes r2 ON r1.estimated_duration_minutes = r2.estimated_duration_minutes AND r1.route_id < r2.route_id;

[User] For each payment status, how many payments were made and what was the total amount paid? Order the results by the total amount paid in descending order.

[Assistant] SELECT status, COUNT(*) AS payment_count, SUM(amount_paid) AS total_amount FROM insurance.premium_payments GROUP BY status ORDER BY total_amount DESC;

[User] Can you find the contract that has emitted the most events, and show its contract ID along with the total number of events emitted?

[Assistant] SELECT contract_id, COUNT(*) AS total_events FROM web3.events GROUP BY contract_id ORDER BY total_events DESC LIMIT 1;

[User] List all notifications sent through the 'Email' channel, showing all columns.

[Assistant] SELECT notification_id, citizen_id, application_id, message_subject, message_body, channel, sent_at, status, related_entity_type, related_entity_id FROM government_services.notifications WHERE channel = 'Email';

[User] List the full names of employees who have verified 'Proof of Identity' documents.

[Assistant] SELECT DISTINCT T1.first_name, T1.last_name FROM government_services.employees AS T1 JOIN government_services.documents AS T2 ON T1.employee_id = T2.verified_by_employee_id WHERE T2.document_type = 'Proof of Identity';


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 token_basic_info ( coin_id text, token_name text, token_symbol text, token_address text, chain text, price numeric, price_change_percentage_1h numeric, price_change_percentage_24h numeric, price_change_percentage_7d numeric, highest_price_24h numeric, lowest_price_24h numeric, market_cap numeric, market_cap_rank numeric, market_cap_change_percentage_24h text, total_volume text, narrative text, trend_rank numeric )
CREATE TABLE narrative_info ( narrative text, top_3_coins text, price_change_percentage_1h numeric, price_change_percentage_24h numeric, price_change_percentage_7d numeric, market_cap numeric, volume_24h numeric, trend_rank numeric, token_num numeric )
CREATE TABLE cex_token_balance ( snapshot_time text, chain text, address text, exchange text, token_address text, token_symbol text, balance numeric, usd_value numeric, price numeric )
CREATE TABLE smart_money_profit ( address text, rank numeric, profit numeric, roi numeric, realized_ratio numeric, most_profit_token text, last_trade_time text, chain text )
CREATE TABLE smart_money_token_inflow ( token_address text, token_symbol text, token_amount numeric, usd_value numeric, avg_price numeric, type numeric, address_amount numeric, narrative text, chain text )
##Table Structure
CREATE TABLE trading_platform.metadata ( metadata_id character varying(64) NOT NULL, asset_id character varying(64) NOT NULL, key character varying(128) NOT NULL, value text NOT NULL, PRIMARY KEY (metadata_id) )
##Table Structure
CREATE TABLE insurance.claims ( claim_id text PRIMARY KEY, policy_id text, customer_id text, incident_date timestamp, reported_date timestamp, description text, estimated_loss numeric, status text, settlement_amount numeric, settlement_date date, claim_handler_id text, police_report_number text )
CREATE TABLE insurance.insurance_products ( product_id text PRIMARY KEY, product_name text, product_type text, description text, base_premium numeric, coverage_details text, underwriting_rules text, is_active boolean, created_at timestamp, updated_at timestamp )
##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 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 )
##Table Structure
CREATE TABLE government_services.notifications ( notification_id.text, citizen_id.text, application_id.text, message_subject.text, message_body.text, channel.text, sent_at.timestamp, status.text, related_entity_type.text, related_entity_id.text )
##Table Structure
CREATE TABLE legal_services.law_firms ( firm_id text PRIMARY KEY, firm_name text, address text, phone text, website text, founded_date date, managing_partner_id text )
##Table Structure
CREATE TABLE government_services.agencies ( agency_id character varying(64) NOT NULL, agency_name character varying(255) NOT NULL, jurisdiction_level character varying(50) NOT NULL, primary_contact_email character varying(128), main_phone_number character varying(32), website_url character varying(255), established_date date, parent_agency_id character varying(64), PRIMARY KEY (agency_id) )
##Table Structure
CREATE TABLE gaming_technology.player_achievements ( player_achievement_id.uuid, player_id.uuid, achievement_id.uuid, unlocked_at.timestamptz )
##Table Structure
CREATE TABLE social_media.conversations ( conversation_id text PRIMARY KEY, created_at timestamp, last_message_at timestamp, is_group_chat bool, group_name text )

[User] For the 'DeFi' narrative, what is the average ROI and the total net inflow (usd_value where type=1) from smart money token inflow?

[Assistant]
SELECT AVG(sm.roi) AS avg_roi, SUM(smt.usd_value) AS total_net_inflow
FROM smart_money_token_inflow smt
JOIN smart_money_profit sm ON smt.chain = sm.chain
WHERE smt.narrative = 'DeFi' AND smt.type = 1;

[User] I need to retrieve asset IDs along with their category and website metadata values for assets that have both entries.

[Assistant]
SELECT m_cat.asset_id,
       m_cat.value AS category,
       m_web.value AS website_url
FROM trading_platform.metadata m_cat
JOIN trading_platform.metadata m_web
  ON m_cat.asset_id = m_web.asset_id
WHERE m_cat.key = 'category'
  AND m_web.key = 'website';

[User] Actually, filter to include only those assets where the category value is 'defi'.

[Assistant]
SELECT m_cat.asset_id,
       m_cat.value AS category,
       m_web.value AS website_url
FROM trading_platform.metadata m_cat
JOIN trading_platform.metadata m_web
  ON m_cat.asset_id = m_web.asset_id
WHERE m_cat.key = 'category'
  AND m_web.key = 'website'
  AND m_cat.value = 'defi';

[User] List all insurance products with their product name and base premium, where the product description contains the word 'accident'.

[Assistant] SELECT product_name, base_premium FROM insurance.insurance_products WHERE description ILIKE '%accident%';

[User] Find pairs of distinct routes that share the same destination location but start from different origins. Include the route ID and route number for both routes and the shared destination 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.destination_location_id AS shared_destination_location_id
FROM transportation.routes AS r1
JOIN transportation.routes AS r2
  ON r1.destination_location_id = r2.destination_location_id
  AND r1.route_id < r2.route_id
WHERE
  r1.origin_location_id != r2.origin_location_id;

[User] Find all vehicles that share the same make and model but were manufactured in different years. Show both vehicle IDs, the make, model, and their respective years.

[Assistant]
SELECT v1.vehicle_id AS vehicle1_id,
       v2.vehicle_id AS vehicle2_id,
       v1.make,
       v1.model,
       v1.year AS year1,
       v2.year AS year2
FROM transportation.vehicles v1
JOIN transportation.vehicles v2
  ON v1.make = v2.make
  AND v1.model = v2.model
  AND v1.year <> v2.year
  AND v1.vehicle_id < v2.vehicle_id;

[User] Find the application IDs for applications that have received notifications through both 'Email' and 'SMS' channels.

[Assistant] SELECT application_id FROM government_services.notifications WHERE channel IN ('Email', 'SMS') GROUP BY application_id HAVING COUNT(DISTINCT channel) = 2;

[User] List all pairs of law firms founded in the same year, showing both firm names and their shared founding year.

[Assistant]
SELECT lf1.firm_name AS firm1, lf2.firm_name AS firm2, EXTRACT(YEAR FROM lf1.founded_date) AS founded_year
FROM legal_services.law_firms lf1
JOIN legal_services.law_firms lf2
  ON EXTRACT(YEAR FROM lf1.founded_date) = EXTRACT(YEAR FROM lf2.founded_date)
  AND lf1.firm_id < lf2.firm_id;

[User] Show each agency along with its parent agency’s name and jurisdiction level.

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

[User] Show me the earliest unlock date for each achievement along with the player_id who unlocked it.

[Assistant] SELECT achievement_id, player_id, MIN(unlocked_at) AS earliest_unlock FROM gaming_technology.player_achievements GROUP BY achievement_id, player_id;

[User] Actually, for each achievement, I only want to see the player who was the very first to unlock it and the corresponding date.

[Assistant] SELECT pa.achievement_id, pa.player_id, pa.unlocked_at AS earliest_unlock FROM gaming_technology.player_achievements pa INNER JOIN ( SELECT achievement_id, MIN(unlocked_at) AS min_unlocked_at FROM gaming_technology.player_achievements GROUP BY achievement_id ) first_unlock ON pa.achievement_id = first_unlock.achievement_id AND pa.unlocked_at = first_unlock.min_unlocked_at;

[User] How many group conversations are there?

[Assistant] SELECT COUNT(*) FROM social_media.conversations WHERE is_group_chat = TRUE;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement. ##Table Structure
CREATE TABLE government_services.employees ( employee_id.text, agency_id.text, first_name.text, last_name.text, job_title.text, department.text, work_email.text, work_phone.text, hire_date.date, termination_date.date, access_level.text, manager_employee_id.text )
##Table Structure
CREATE TABLE insurance.claim_documents ( document_id character varying(64) NOT NULL, claim_id character varying(64) NOT NULL, document_type character varying(50) NOT NULL, file_name character varying(255) NOT NULL, file_path character varying(512) NOT NULL, file_size_bytes integer, mime_type character varying(100), uploaded_by character varying(64), uploaded_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, description text, PRIMARY KEY (document_id) )
##Table Structure
CREATE TABLE insurance.insurance_products ( product_id text PRIMARY KEY, product_name text, product_type text, description text, base_premium numeric, coverage_details text, underwriting_rules text, is_active boolean, created_at timestamp, updated_at timestamp )
##Table Structure
CREATE TABLE smart_money_profit ( address.text, rank.numeric, profit.numeric, roi.numeric, realized_ratio.numeric, most_profit_token.text, last_trade_time.text, chain.text )
##Table Structure
CREATE TABLE 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 healthcare.medical_records ( record_id.text, patient_id.text, appointment_id.text, doctor_id.text, record_date.timestamp, chief_complaint.text, present_illness_history.text, past_medical_history.text, physical_examination_notes.text, assessment.text, treatment_plan.text, vitals.json, created_at.timestamp )
CREATE TABLE healthcare.patient_insurance ( patient_insurance_id.text, patient_id.text, plan_id.text, policy_number.text, group_number.text, subscriber_name.text, effective_date.date, expiration_date.date, is_primary.boolean )
##Table Structure
CREATE TABLE web3.tokens ( token_id text PRIMARY KEY, contract_address text, token_name text, token_symbol text, decimals int, total_supply numeric )
##Table Structure
CREATE TABLE government_services.agencies ( agency_id character varying(64) NOT NULL, agency_name character varying(255) NOT NULL, jurisdiction_level character varying(50) NOT NULL, primary_contact_email character varying(128), main_phone_number character varying(32), website_url character varying(255), established_date date, parent_agency_id character varying(64), PRIMARY KEY (agency_id) )
CREATE TABLE government_services.appointments ( appointment_id character varying(64) NOT NULL, citizen_id character varying(64) NOT NULL, employee_id character varying(64), location_id character varying(64), service_id character varying(64), scheduled_start_time timestamp NOT NULL, scheduled_end_time timestamp, purpose text NOT NULL, status character varying(30) NOT NULL, booking_method character varying(50), created_at timestamp NOT NULL, notes text, PRIMARY KEY (appointment_id) )
##Table Structure
CREATE TABLE trading_platform.logs ( log_id character varying(64) NOT NULL, user_id character varying(64), action character varying(128) NOT NULL, details text NOT NULL, logged_at timestamp NOT NULL, PRIMARY KEY (log_id) )
##Table Structure
CREATE TABLE web3.token_transfers ( transfer_id text, token_id text, from_address text, to_address text, value numeric, transaction_id text, log_index integer )
##Table Structure
CREATE TABLE 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 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 )

[User] List the full names and hire dates of all employees who report directly to a manager with the job title 'Director'.

[Assistant]
SELECT e.first_name, e.last_name, e.hire_date
FROM government_services.employees e
JOIN government_services.employees m ON e.manager_employee_id = m.employee_id
WHERE m.job_title = 'Director';

[User] Which document types have been used for more than 100 documents, and what is the total file size across all documents of each such type?

[Assistant]
SELECT document_type, COUNT(*) AS document_count, SUM(file_size_bytes) AS total_file_size_bytes
FROM insurance.claim_documents
GROUP BY document_type
HAVING COUNT(*) > 100;

[User] Which insurance products have 'comprehensive' in their coverage details? Show the product_id and product_name.

[Assistant] SELECT product_id, product_name FROM insurance.insurance_products WHERE coverage_details ILIKE '%comprehensive%';

[User] Can you also add the product_type to the output?

[Assistant] SELECT product_id, product_name, product_type FROM insurance.insurance_products WHERE coverage_details ILIKE '%comprehensive%';

[User] Which smart money address on the Ethereum chain has the lowest ROI, and what are their profit and rank?

[Assistant] SELECT address, roi, profit, rank FROM smart_money_profit WHERE chain = 'Ethereum' ORDER BY roi ASC LIMIT 1;

[User] Can you also include the realized_ratio for this address?

[Assistant] SELECT address, roi, profit, rank, realized_ratio FROM smart_money_profit WHERE chain = 'Ethereum' ORDER BY roi ASC LIMIT 1;

[User] Provide a count of agencies grouped by their jurisdiction level.

[Assistant] SELECT jurisdiction_level, COUNT(*) FROM government_services.agencies GROUP BY jurisdiction_level;

[User] List all primary insurance policies that will expire within the next 30 days. Return patient_insurance_id, patient_id, policy_number, and expiration_date.

[Assistant]
SELECT patient_insurance_id,
       patient_id,
       policy_number,
       expiration_date
FROM healthcare.patient_insurance
WHERE is_primary = TRUE
  AND expiration_date BETWEEN CURRENT_DATE AND CURRENT_DATE + INTERVAL '30 days';

[User] What is the average total_supply for each decimals value?

[Assistant]
SELECT decimals, AVG(total_supply) AS avg_supply
FROM web3.tokens
GROUP BY decimals;

[User] Actually, I only want to include tokens whose token_symbol starts with 'A'.

[Assistant]
SELECT decimals, AVG(total_supply) AS avg_supply
FROM web3.tokens
WHERE token_symbol LIKE 'A%'
GROUP BY decimals;

[User] List the name of each agency and the number of appointments associated with services from that agency.

[Assistant] SELECT T1.agency_name, COUNT(T2.appointment_id) FROM agencies AS T1 JOIN appointments AS T2 ON T1.agency_id = T2.agency_id GROUP BY T1.agency_name;

[User] For each user, list all the distinct actions they have performed along with the count of each action.

[Assistant] SELECT user_id, action, COUNT(*) FROM trading_platform.logs GROUP BY user_id, action ORDER BY user_id, action;

[User] Now, only show users who have performed more than 5 distinct actions.

[Assistant] SELECT user_id FROM trading_platform.logs GROUP BY user_id HAVING COUNT(DISTINCT action) > 5 ORDER BY user_id;

[User] Which addresses have both sent and received tokens? List them.

[Assistant] SELECT DISTINCT t1.from_address FROM web3.token_transfers t1 INNER JOIN web3.token_transfers t2 ON t1.from_address = t2.to_address;

[User] Can you also include how many tokens each of these addresses have sent and received?

[Assistant] SELECT addr, SUM(sent) AS total_sent, SUM(received) AS total_received FROM (SELECT from_address AS addr, SUM(value) AS sent, 0 AS received FROM web3.token_transfers GROUP BY from_address UNION ALL SELECT to_address AS addr, 0 AS sent, SUM(value) AS received FROM web3.token_transfers GROUP BY to_address) AS combined GROUP BY addr HAVING SUM(sent) > 0 AND SUM(received) > 0;

[User] Show all projects that raised funds in February 2022, including their names and investment values.

[Assistant] SELECT project_name, investment_value FROM project_fundraising_record WHERE investment_date LIKE '2022-02%';

[User] Count the total number of users who have enabled email notifications but disabled push notifications.

[Assistant] SELECT COUNT(*) FROM social_media.user_settings WHERE email_notifications_enabled = TRUE AND push_notifications_enabled = FALSE;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement. ##Table Structure
CREATE TABLE government_services.notifications ( notification_id.text, citizen_id.text, application_id.text, message_subject.text, message_body.text, channel.text, sent_at.timestamp, status.text, related_entity_type.text, related_entity_id.text )
##Table Structure
CREATE TABLE insurance.customers ( customer_id.text, first_name.text, last_name.text, date_of_birth.date, ssn_hash.text, address_line1.text, address_line2.text, city.text, state.text, zip_code.text, country.text, phone_number.text, email.text, created_at.timestamp, updated_at.timestamp, status.text )
CREATE TABLE insurance.policies ( policy_id text, customer_id text, product_id text, agent_id text, policy_number text, start_date date, end_date date, premium_amount numeric, coverage_limit numeric, deductible numeric, status text, issued_at timestamp, cancellation_date date, cancellation_reason text )
CREATE TABLE insurance.claims ( claim_id text PRIMARY KEY, policy_id text, customer_id text, incident_date timestamp, reported_date timestamp, description text, estimated_loss numeric, status text, settlement_amount numeric, settlement_date date, claim_handler_id text, police_report_number text )
CREATE TABLE insurance.insurance_products ( product_id text PRIMARY KEY, product_name text, product_type text, description text, base_premium numeric, coverage_details text, underwriting_rules text, is_active boolean, created_at timestamp, updated_at timestamp )
CREATE TABLE insurance.agents ( agent_id.text, first_name.text, last_name.text, agency_name.text, license_number.text, license_state.text, contact_email.text, contact_phone.text, hire_date.date, termination_date.date, status.text, commission_rate.numeric, manager_id.text )
CREATE TABLE insurance.policy_beneficiaries ( beneficiary_id text, policy_id text, customer_id text, first_name text, last_name text, relationship text, percentage_share numeric, contact_info text, added_at timestamp )
##Table Structure
CREATE TABLE web3.wallets ( wallet_id text, user_id text, address text, private_key text, created_at timestamp )
##Table Structure
CREATE TABLE hospitality_technology.rooms ( room_id text, property_id text, room_number text, room_type_id text, floor integer, status text, is_smoking boolean, features text, current_condition text, last_cleaned_at timestamp )
##Table Structure
CREATE TABLE web3.events ( event_id text PRIMARY KEY, contract_id text, event_name text, data text, emitted_at timestamp, transaction_id text, log_index int )
CREATE TABLE web3.token_transfers ( transfer_id text PRIMARY KEY, token_id text, from_address text, to_address text, value numeric, transaction_id text, log_index int )
##Table Structure
CREATE TABLE government_services.notifications ( notification_id character varying(64) NOT NULL, citizen_id character varying(64) NOT NULL, application_id character varying(64), message_subject character varying(255), message_body text NOT NULL, channel character varying(30) NOT NULL, sent_at timestamp NOT NULL, status character varying(30) NOT NULL, related_entity_type character varying(50), related_entity_id character varying(64), PRIMARY KEY (notification_id) )
##Table Structure
CREATE TABLE social_media.comments ( comment_id text PRIMARY KEY, post_id text, user_id text, parent_comment_id text, content text, created_at timestamp, updated_at timestamp )
##Table Structure
CREATE TABLE legal_services.clients ( client_id text, first_name text, last_name text, company_name text, email text, phone text, address text, date_registered timestamp, status text )
CREATE TABLE legal_services.lawyers ( lawyer_id text, first_name text, last_name text, bar_number text, firm_id text, email text, phone text, specialization text, hire_date timestamp, is_partner boolean )
CREATE TABLE legal_services.law_firms ( firm_id text, firm_name text, address text, phone text, website text, founded_date date, managing_partner_id text )
CREATE TABLE legal_services.documents ( document_id text, case_id text, document_name text, document_type text, storage_path text, uploaded_by_lawyer_id text, upload_timestamp timestamp, version integer, description text )
CREATE TABLE legal_services.time_entries ( entry_id text, case_id text, lawyer_id text, date_worked date, hours_spent numeric, billing_rate numeric, description text, is_billable boolean, is_billed boolean, invoice_id text, created_at timestamp )
CREATE TABLE legal_services.appointments ( appointment_id text, client_id text, lawyer_id text, case_id text, start_time timestamp, end_time timestamp, location text, subject text, notes text, status text, created_at timestamp )
##Table Structure
CREATE TABLE legal_services.lawyers ( lawyer_id.text, first_name.text, last_name.text, bar_number.text, firm_id.text, email.text, phone.text, specialization.text, hire_date.timestamp, is_partner.boolean )
##Table Structure
CREATE TABLE legal_services.cases ( case_id.text, case_number.text, case_name.text, client_id.text, lead_lawyer_id.text, case_type.text, status.text, date_opened.timestamp, date_closed.timestamp, description.text, court_jurisdiction.text )

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement. ##Table Structure
// Use Hashes for ticket details. Key format: ticket:<ticket_id>
// HSET ticket:tkt_1a2b ticket_id "tkt_1a2b" booking_id "book_zyx" car_id "car_abc" seat_number "12A" ... is_checked_in 0 ...

// To link tickets to bookings (optional):
// SADD booking:book_zyx:tickets ticket:tkt_1a2b
// Use Hashes for maintenance record details. Key format: maintenance_record:<record_id>
// HSET maintenance_record:maint_rec_001 record_id "maint_rec_001" asset_id "train_789" asset_type "Train" ... status "Completed"

// To link records to assets (optional):
// SADD train:train_789:maintenance maintenance_record:maint_rec_001
// SADD platform:plat_123:maintenance maintenance_record:maint_rec_002
##Table Structure
CREATE TABLE web3.events ( event_id text, contract_id text, event_name text, data text, emitted_at timestamp, transaction_id text, log_index integer )
CREATE TABLE web3.transactions ( transaction_id text, from_address text, to_address text, value numeric, gas_used integer, gas_price numeric, block_number integer, timestamp timestamp, input_data text, status text, nonce integer )
CREATE TABLE web3.tokens ( token_id text, contract_address text, token_name text, token_symbol text, decimals integer, total_supply numeric )
CREATE TABLE web3.token_transfers ( transfer_id text, token_id text, from_address text, to_address text, value numeric, transaction_id text, log_index integer )
CREATE TABLE web3.wallets ( wallet_id text, user_id text, address text, private_key text, created_at timestamp )
##Table Structure
CREATE TABLE transportation.trips ( trip_id character varying(64) NOT NULL, route_id character varying(64), vehicle_id character varying(64) NOT NULL, driver_id character varying(64) NOT NULL, scheduled_departure timestamp with time zone NOT NULL, actual_departure timestamp with time zone, scheduled_arrival timestamp with time zone NOT NULL, actual_arrival timestamp with time zone, origin_location_id character varying(64) NOT NULL, destination_location_id character varying(64) NOT NULL, status character varying(32) NOT NULL, passenger_count integer, cargo_manifest_id character varying(64), PRIMARY KEY (trip_id) )
##Table Structure
CREATE TABLE hospitality_technology.rooms ( room_id character varying(64) NOT NULL, property_id character varying(64) NOT NULL, room_number character varying(10) NOT NULL, room_type_id character varying(64) NOT NULL, floor integer, status character varying(50) NOT NULL, is_smoking boolean NOT NULL DEFAULT false, features text, current_condition text, last_cleaned_at timestamp with time zone, PRIMARY KEY (room_id), FOREIGN KEY (property_id) REFERENCES hospitality_technology.properties(property_id), FOREIGN KEY (room_type_id) REFERENCES hospitality_technology.room_types(room_type_id) )
CREATE TABLE hospitality_technology.reservations ( reservation_id character varying(64) NOT NULL, property_id character varying(64) NOT NULL, guest_id character varying(64) NOT NULL, room_id character varying(64), room_type_id character varying(64) NOT NULL, check_in_date date NOT NULL, check_out_date date NOT NULL, actual_check_in_ts timestamp with time zone, actual_check_out_ts timestamp with time zone, num_adults integer NOT NULL, num_children integer DEFAULT 0, status character varying(50) NOT NULL, booking_source character varying(100), rate_plan_id character varying(64), total_amount numeric(12, 2), amount_paid numeric(12, 2) DEFAULT 0.00, special_requests text, created_at timestamp with time zone NOT NULL DEFAULT current_timestamp, updated_at timestamp with time zone NOT NULL DEFAULT current_timestamp, PRIMARY KEY (reservation_id), FOREIGN KEY (property_id) REFERENCES hospitality_technology.properties(property_id), FOREIGN KEY (guest_id) REFERENCES hospitality_technology.guests(guest_id), FOREIGN KEY (room_id) REFERENCES hospitality_technology.rooms(room_id), FOREIGN KEY (room_type_id) REFERENCES hospitality_technology.room_types(room_type_id) )
##Table Structure
CREATE TABLE government_services.employees (
    employee_id character varying(64) NOT NULL, -- unique identifier for the government employee
    agency_id character varying(64) NOT NULL, -- FK to agencies table
    first_name character varying(100) NOT NULL,
    last_name character varying(100) NOT NULL,
    job_title character varying(150) NOT NULL,
    department character varying(100),
    work_email character varying(128) NOT NULL UNIQUE,
    work_phone character varying(32),
    hire_date date NOT NULL,
    termination_date date, -- null if currently employed
    access_level character varying(50), -- Role or permission level
    manager_employee_id character varying(64), -- FK to self for reporting structure
    PRIMARY KEY (employee_id)
)
##Table Structure
CREATE TABLE web3.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] 特定のプラットフォームID 'plat_123' に関連するメンテナンス記録を取得するのを手伝っていただけますか？また、記録のステータスも含めてください。

[Assistant]
SMEMBERS platform:plat_123:maintenance
HGETALL maintenance_record:<record_id>

[User] ステータスが 'Completed' の記録だけを表示するようにフィルタリングしていただけますか？

[Assistant]
SMEMBERS platform:plat_123:maintenance
HGET maintenance_record:<record_id> status
HGETALL maintenance_record:<record_id> (only if status = 'Completed')

[User] 関連する資産タイプも結果に含めていただけますか？

[Assistant]
SMEMBERS platform:plat_123:maintenance
HGET maintenance_record:<record_id> status
HGETALL maintenance_record:<record_id> (only if status = 'Completed')

[User] For each wallet, show the wallet address and the total value of tokens they have received across all token transfers.

[Assistant]
SELECT w.address, COALESCE(SUM(tt.value), 0) AS total_received_value
FROM web3.wallets w
LEFT JOIN web3.token_transfers tt ON w.address = tt.to_address
GROUP BY w.address;

[User] What is the count of trips for each status?

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

[User] Only include statuses with more than 5 trips.

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

[User] Show me all reservations with their reservation_id, room_number, room status, and check_in_date.

[Assistant]
SELECT r.reservation_id,
       rm.room_number,
       rm.status AS room_status,
       r.check_in_date
FROM hospitality_technology.reservations r
LEFT JOIN hospitality_technology.rooms rm
  ON r.room_id = rm.room_id;

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

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

[User] For each transaction, find the next transaction by the same sender. Show the original transaction_id as current_tx, the next transaction_id as next_tx, from_address, and the time difference in minutes between them.

[Assistant]
SELECT t1.transaction_id AS current_tx,
       t2.transaction_id AS next_tx,
       t1.from_address,
       EXTRACT(EPOCH FROM (t2.timestamp - t1.timestamp)) / 60 AS diff_minutes
FROM web3.transactions t1
JOIN web3.transactions t2
  ON t1.from_address = t2.from_address
  AND t2.timestamp = (
    SELECT MIN(t3.timestamp)
    FROM web3.transactions t3
    WHERE t3.from_address = t1.from_address
      AND t3.timestamp > t1.timestamp
  );


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement. ##Table Structure
CREATE TABLE smart_money_token_inflow ( token_address character varying(100) NOT NULL, -- the token's address token_symbol character varying(100), -- the tokens's symbol token_amount numeric(38,2), -- the absolute value of the amount if user bought minus  the amount user sold of this token usd_value numeric(38,2), -- the absolute usd value of the bought token minus sold token avg_price numeric(38,6), -- the average cost price of user spent on this token type int, -- the direction of the trade on this token. 1 means buying, 2 means selling address_amount integer, -- the amount of the user bought this token narrative character varying(100), -- the category or narrative of the token chain character varying(100), -- the chain that the token resides ,PRIMARY KEY (token_address, chain) )
##Table Structure
CREATE TABLE trading_platform.logs ( log_id text PRIMARY KEY, user_id text, action text, details text, logged_at timestamp )
##Table Structure
CREATE TABLE healthcare.appointments (
    appointment_id character varying(64) NOT NULL, -- unique identifier for the appointment
    patient_id character varying(64) NOT NULL, -- FK to patients table
    doctor_id character varying(64) NOT NULL, -- FK to doctors table
    appointment_time timestamp with time zone NOT NULL, -- date and time of the appointment
    duration_minutes integer NOT NULL, -- expected duration in minutes
    reason text, -- reason for the visit
    status character varying(32) NOT NULL, -- e.g., Scheduled, Completed, Cancelled, No-show
    location_id character varying(64), -- FK to a potential locations/clinics table
    notes text, -- notes related to scheduling
    created_at timestamp with time zone NOT NULL DEFAULT current_timestamp,
    PRIMARY KEY (appointment_id)
)
##Table Structure
CREATE TABLE trading_platform.trades (
    trade_id character varying(64) NOT NULL,  -- unique identifier for the trade
    order_id character varying(64) NOT NULL, -- identifier of the order that led to the trade
    buyer_id character varying(64) NOT NULL, -- identifier of the buyer
    seller_id character varying(64) NOT NULL, -- identifier of the seller
    asset_id character varying(64) NOT NULL, -- identifier of the asset being traded
    quantity numeric(38,14) NOT NULL, -- quantity of the asset in the trade
    price numeric(38,14) NOT NULL, -- price per unit of the asset
    traded_at timestamp NOT NULL, -- time when the trade was executed
    PRIMARY KEY (trade_id)
)
##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 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, 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 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 )

[User] For each chain, which token had the highest number of smart money addresses buying it this week? Show the token symbol and narrative too.

[Assistant] SELECT chain, token_symbol, narrative, MAX(address_amount) AS max_buyers FROM smart_money_token_inflow WHERE type = 1 AND DATE_TRUNC('week', CURRENT_DATE) = DATE_TRUNC('week', CURRENT_DATE) GROUP BY chain, token_symbol, narrative;

[User] I got an error, I think the filter for the week may be wrong. Please revise the query so that it only counts buys from the current week.

[Assistant] SELECT chain, token_symbol, narrative, address_amount AS buyers FROM smart_money_token_inflow WHERE type = 1 AND EXTRACT(week FROM CURRENT_DATE) = EXTRACT(week FROM CURRENT_DATE) AND EXTRACT(year FROM CURRENT_DATE) = EXTRACT(year FROM CURRENT_DATE) ORDER BY chain, buyers DESC;

[User] For each user, retrieve their most recent log entry, including the action and timestamp.

[Assistant] SELECT l.user_id, l.action, l.logged_at FROM trading_platform.logs l JOIN (SELECT user_id, MAX(logged_at) AS max_time FROM trading_platform.logs GROUP BY user_id) m ON l.user_id = m.user_id AND l.logged_at = m.max_time;

[User] Exclude any logs where the action contains the word 'error'.

[Assistant] SELECT l.user_id, l.action, l.logged_at FROM trading_platform.logs l JOIN (SELECT user_id, MAX(logged_at) AS max_time FROM trading_platform.logs GROUP BY user_id) m ON l.user_id = m.user_id AND l.logged_at = m.max_time WHERE l.action NOT ILIKE '%error%';

[User] Show me all appointments scheduled to last exactly 60 minutes.

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

[User] What is the average trade price for each asset for trades executed between '2024-05-01' and '2024-05-31'?

[Assistant]
SELECT
  asset_id,
  AVG(price) AS avg_price
FROM trading_platform.trades
WHERE traded_at >= '2024-05-01' AND traded_at < '2024-06-01'
GROUP BY asset_id;

[User] Could you list all pairs of developers that are based in the same country and share the same website domain?

[Assistant]
SELECT
  d1.name AS developer1_name,
  d2.name AS developer2_name,
  d1.country,
  d1.website
FROM
  gaming_technology.developers AS d1
JOIN
  gaming_technology.developers AS d2 ON d1.country = d2.country
  AND d1.website = d2.website
  AND d1.developer_id < d2.developer_id
WHERE
  d1.country IS NOT NULL
  AND d1.website IS NOT NULL AND d1.website != '';

[User] Find pairs of notifications for the same application where one was sent via 'Email' and the other via 'SMS'. Display the application_id, email_notification_id, sms_notification_id, email_sent_at, and sms_sent_at.

[Assistant]
SELECT
  n_email.application_id,
  n_email.notification_id AS email_notification_id,
  n_sms.notification_id AS sms_notification_id,
  n_email.sent_at         AS email_sent_at,
  n_sms.sent_at           AS sms_sent_at
FROM government_services.notifications n_email
JOIN government_services.notifications n_sms
  ON n_email.application_id = n_sms.application_id
  AND n_email.channel = 'Email'
  AND n_sms.channel = 'SMS';

[User] Find all pairs of transactions where the gas price of the first transaction is lower than the gas price of the second transaction, but they are both from the same sender address. Show both transaction IDs, the common sender address, and the gas price for each.

[Assistant] SELECT T1.transaction_id AS lower_gas_tx_id, T2.transaction_id AS higher_gas_tx_id, T1.from_address, T1.gas_price AS lower_gas_price, T2.gas_price AS higher_gas_price FROM web3.transactions AS T1 JOIN web3.transactions AS T2 ON T1.from_address = T2.from_address AND T1.gas_price < T2.gas_price;

[User] Show me all user IDs who changed their profile settings after June 1, 2024.

[Assistant] SELECT user_id FROM social_media.user_settings WHERE updated_at > '2024-06-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 web3.events (
    event_id character varying(64) NOT NULL,  -- unique identifier for the event
    contract_id character varying(64) NOT NULL, -- identifier of the contract emitting the event
    event_name character varying(128) NOT NULL, -- name of the event
    data text NOT NULL, -- data payload of the event
    emitted_at timestamp NOT NULL, -- time when the event was emitted
    transaction_id character varying(64) NOT NULL, -- identifier of the transaction that triggered the event
    log_index integer NOT NULL, -- index of the event log in the transaction
    PRIMARY KEY (event_id)
)
CREATE TABLE web3.transactions ( transaction_id character varying(64) NOT NULL, from_address character varying(128) NOT NULL, to_address character varying(128), value numeric(38,14) NOT NULL, gas_used integer NOT NULL, gas_price numeric(38,14) NOT NULL, block_number integer NOT NULL, timestamp timestamp NOT NULL, input_data text, status character varying(32) NOT NULL, nonce integer NOT NULL, PRIMARY KEY (transaction_id) )
CREATE TABLE web3.token_transfers ( transfer_id text, token_id text, from_address text, to_address text, value numeric, transaction_id text, log_index integer )
##Table Structure
CREATE TABLE healthcare.doctors ( doctor_id.text, first_name.text, last_name.text, specialty.text, license_number.text, phone_number.text, email.text, hospital_affiliation_id.text, created_at.timestamp, updated_at.timestamp )
CREATE TABLE healthcare.diagnoses ( diagnosis_id.text, record_id.text, patient_id.text, doctor_id.text, diagnosis_code.text, code_type.text, description.text, diagnosis_date.date, status.text, is_chronic.boolean )
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.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 insurance.insurance_products ( product_id text PRIMARY KEY, product_name text, product_type text, description text, base_premium numeric, coverage_details text, underwriting_rules text, is_active boolean, created_at timestamp, updated_at timestamp )
##Table Structure
CREATE TABLE web3.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 web3.wallets ( wallet_id.text, user_id.text, address.text, private_key.text, created_at.timestamp )
##Table Structure
CREATE TABLE transportation.locations ( location_id text, name text, type text, address_line1 text, city text, state_province text, postal_code text, country text, latitude numeric, longitude numeric, timezone text )
##Table Structure
CREATE TABLE token_dexpool_info ( pair_address character varying(512) NOT NULL, -- the id of dexpool token_name character varying(100) NOT NULL, -- the name of the token in the dexpool token_symbol character varying(100) NOT NULL, -- the token's symbol chain text, -- the chain that the dexpool resides price double precision, -- the current price of the token price_change_percentage_1h double precision, -- change in value divided by the absolute price value of the original token price in 1 hour price_change_percentage_6h double precision, -- change in value divided by the absolute price value of the original token price in 6 hours price_change_percentage_24h double precision, -- change in value divided by the absolute price value of the original token price in 24 hours makers_24h double precision, -- the makers of the dex pool in 24 hours volume_24h double precision, -- the trade volume of the dex pool in 24 hours liquidity double precision, -- the liquidity of the dex pool market_cap double precision, -- the market cap of the token trend_rank bigint, -- the rank of token in the dex pool of recent trending, value 1 expresses the most popular token. ,PRIMARY KEY (pair_address, chain) )
##Table Structure
CREATE TABLE web3.wallets ( wallet_id text PRIMARY KEY, user_id text, address text, private_key text, created_at timestamp )

[User] Show the transaction ID, the transaction value from the transactions table, and the sum of the value from token_transfers for all transactions that have at least one associated token transfer. Name the sum column total_token_transfer_value.

[Assistant] SELECT t.transaction_id, t.value AS transaction_native_value, SUM(tt.value) AS total_token_transfer_value FROM web3.transactions t JOIN web3.token_transfers tt ON t.transaction_id = tt.transaction_id GROUP BY t.transaction_id, t.value;

[User] List all chronic diagnoses made by Cardiology specialists in the last year, including the patient ID, diagnosis description, and doctor's full name.

[Assistant] SELECT dg.patient_id, dg.description, d.first_name || ' ' || d.last_name AS doctor_name FROM healthcare.diagnoses dg JOIN healthcare.doctors d ON dg.doctor_id = d.doctor_id WHERE d.specialty = 'Cardiology' AND dg.is_chronic = TRUE AND dg.diagnosis_date >= CURRENT_DATE - INTERVAL '1 year';

[User] List all pairs of insurance products that share the same product_type but have differing active statuses. Return both product_ids, the product_type, and each is_active flag.

[Assistant]
SELECT p1.product_id AS product_id_1, p2.product_id AS product_id_2, p1.product_type, p1.is_active AS is_active_1, p2.is_active AS is_active_2
FROM insurance.insurance_products p1
JOIN insurance.insurance_products p2
  ON p1.product_type = p2.product_type
  AND p1.is_active <> p2.is_active
WHERE p1.product_id < p2.product_id;

[User] List the total value and count of transactions for each status, ordered by total value descending.

[Assistant]
SELECT status, COUNT(*) AS transaction_count, SUM(value) AS total_value
FROM web3.transactions
GROUP BY status
ORDER BY total_value DESC;

[User] Actually, can you also include the average value per transaction for each status?

[Assistant]
SELECT status, COUNT(*) AS transaction_count, SUM(value) AS total_value, AVG(value) AS avg_value
FROM web3.transactions
GROUP BY status
ORDER BY total_value DESC;

[User] List all pairs of wallet IDs where both wallets were created on the same day but belong to different users, showing the user IDs and the creation date.

[Assistant] SELECT w1.wallet_id AS wallet_id_1, w2.wallet_id AS wallet_id_2, w1.user_id AS user_id_1, w2.user_id AS user_id_2, DATE(w1.created_at) AS creation_date FROM web3.wallets w1 JOIN web3.wallets w2 ON DATE(w1.created_at) = DATE(w2.created_at) AND w1.user_id <> w2.user_id AND w1.wallet_id < w2.wallet_id;

[User] Find pairs of distinct locations in the same city that have different types. Include location IDs, names, city, and type for both locations.

[Assistant] SELECT l1.location_id AS location1_id, l1.name AS location1_name, l1.city, l1.type AS location1_type, l2.location_id AS location2_id, l2.name AS location2_name, l2.type AS location2_type FROM transportation.locations AS l1 JOIN transportation.locations AS l2 ON l1.city = l2.city AND l1.location_id < l2.location_id WHERE l1.type != l2.type;

[User] List tokens with trend rank 5 or better and a price below $1. Show symbol, price, and trend rank.

[Assistant] SELECT token_symbol, price, trend_rank FROM token_dexpool_info WHERE trend_rank IS NOT NULL AND trend_rank <= 5 AND price < 1;

[User] For each wallet, find the previous wallet created by the same user. Show current wallet_id, previous_wallet_id, user_id, and the difference in days between their creation dates.

[Assistant]
SELECT
  wallet_id AS current_wallet_id,
  LAG(wallet_id) OVER (PARTITION BY user_id ORDER BY created_at) AS previous_wallet_id,
  user_id,
  EXTRACT(EPOCH FROM (
    created_at - LAG(created_at) OVER (PARTITION BY user_id ORDER BY created_at)
  )) / 86400 AS diff_days
FROM web3.wallets;