System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement. ##Table Structure
CREATE TABLE government_services.citizens ( citizen_id text PRIMARY KEY, national_id_number text, first_name text, last_name text, date_of_birth date, gender text, primary_address text, contact_email text, contact_phone text, registration_date timestamp, is_verified boolean )
CREATE TABLE government_services.services ( service_id text PRIMARY KEY, agency_id text, service_name text, description text, category text, eligibility_criteria text, standard_fee numeric, average_processing_time_days int, is_active boolean, online_application_url text )
CREATE TABLE government_services.payments ( payment_id text PRIMARY KEY, application_id text, citizen_id text, service_id text, amount numeric, currency text, payment_method text, payment_provider_reference text, payment_timestamp timestamp, status text, notes text )
CREATE TABLE government_services.employees ( employee_id text PRIMARY KEY, agency_id text, first_name text, last_name text, job_title text, department text, work_email text, work_phone text, hire_date date, termination_date date, access_level text, manager_employee_id text )
CREATE TABLE government_services.notifications ( notification_id text PRIMARY KEY, citizen_id text, application_id text, message_subject text, message_body text, channel text, sent_at timestamp, status text, related_entity_type text, related_entity_id text )
##Table Structure
CREATE TABLE social_media.users ( user_id text, username text, email text, password_hash text, full_name text, profile_picture_url text, bio text, location text, created_at timestamp, updated_at timestamp, is_verified boolean )
CREATE TABLE social_media.posts ( post_id text PRIMARY KEY, user_id text, content text, media_url text, media_type text, created_at timestamp, updated_at timestamp, visibility text, location_lat numeric, location_lon numeric )
CREATE TABLE social_media.comments ( comment_id.text, post_id.text, user_id.text, parent_comment_id.text, content.text, created_at.timestamp, updated_at.timestamp )
CREATE TABLE social_media.likes ( like_id text PRIMARY KEY, user_id text, post_id text, comment_id text, created_at timestamp )
CREATE TABLE social_media.follows ( follow_id character varying(64) NOT NULL, follower_user_id character varying(64) NOT NULL, following_user_id character varying(64) NOT NULL, created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, PRIMARY KEY (follow_id), CONSTRAINT unique_follow UNIQUE (follower_user_id, following_user_id) )
CREATE TABLE social_media.post_hashtags ( post_hashtag_id text, post_id text, hashtag_id text )
CREATE TABLE social_media.conversations ( conversation_id.text, created_at.timestamp, last_message_at.timestamp, is_group_chat.boolean, group_name.text )
CREATE TABLE social_media.conversation_participants ( participant_id.text, conversation_id.text, user_id.text, joined_at.timestamp, last_read_at.timestamp )
CREATE TABLE social_media.notifications ( notification_id character varying(64) NOT NULL, recipient_user_id character varying(64) NOT NULL, sender_user_id character varying(64), notification_type character varying(30) NOT NULL, target_entity_id character varying(64), target_entity_type character varying(20), created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, read_at timestamp, PRIMARY KEY (notification_id) )
CREATE TABLE social_media.user_settings ( setting_id text PRIMARY KEY, user_id text, theme text, email_notifications_enabled bool, push_notifications_enabled bool, private_profile bool, updated_at timestamp )
##Table Structure
CREATE TABLE social_media.comments (
    comment_id character varying(64) NOT NULL, -- unique identifier for the comment
    post_id character varying(64) NOT NULL, -- identifier of the post being commented on (FK to posts.post_id)
    user_id character varying(64) NOT NULL, -- identifier of the user who made the comment (FK to users.user_id)
    parent_comment_id character varying(64), -- identifier of the parent comment if it's a reply (FK to comments.comment_id)
    content text NOT NULL, -- textual content of the comment
    created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, -- timestamp of comment creation
    updated_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, -- timestamp of last comment edit
    PRIMARY KEY (comment_id)
)
##Table Structure
CREATE TABLE financial_services.securities ( security_id text, ticker_symbol text, isin_code text, cusip_code text, security_name text, security_type text, exchange text, currency text, issuer_name text, sector text, last_updated timestamp )
##Table Structure
CREATE TABLE healthcare.appointments ( appointment_id text, patient_id text, doctor_id text, appointment_time timestamp, duration_minutes integer, reason text, status text, location_id text, notes text, created_at timestamp )
##Table Structure
CREATE TABLE hospitality_technology.room_types ( room_type_id text PRIMARY KEY, property_id text, type_name text, description text, base_rate numeric, max_occupancy int, bed_type text, area_sqft numeric, amenities text )

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

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

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

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

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

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

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

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

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

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

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

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

[User] Sort the results by avg_name_length descending.

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

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

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

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

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

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

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

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

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


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement. ##Table Structure
CREATE TABLE 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 )
##Table Structure
CREATE TABLE legal_services.invoices ( invoice_id text PRIMARY KEY, invoice_number text UNIQUE, client_id text, case_id text, issue_date date, due_date date, total_amount numeric, amount_paid numeric, status text, payment_date timestamp, notes text, created_at timestamp )
##Table Structure
CREATE TABLE legal_services.lawyers ( lawyer_id character varying(64) NOT NULL, first_name character varying(100) NOT NULL, last_name character varying(100) NOT NULL, bar_number character varying(64) UNIQUE NOT NULL, firm_id character varying(64), email character varying(128) UNIQUE NOT NULL, phone character varying(32), specialization text, hire_date timestamp NOT NULL, is_partner boolean DEFAULT false, PRIMARY KEY (lawyer_id) )
CREATE TABLE legal_services.documents ( document_id character varying(64) NOT NULL, case_id character varying(64) NOT NULL, document_name character varying(255) NOT NULL, document_type character varying(100), storage_path text NOT NULL, uploaded_by_lawyer_id character varying(64), upload_timestamp timestamp NOT NULL, version integer DEFAULT 1, description text, PRIMARY KEY (document_id) )
CREATE TABLE legal_services.invoices ( invoice_id character varying(64) NOT NULL, invoice_number character varying(100) UNIQUE NOT NULL, client_id character varying(64) NOT NULL, case_id character varying(64), issue_date date NOT NULL, due_date date NOT NULL, total_amount numeric(12, 2) NOT NULL, amount_paid numeric(12, 2) DEFAULT 0.00, status character varying(50) NOT NULL, payment_date timestamp, notes text, created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, PRIMARY KEY (invoice_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 )
CREATE TABLE social_media.likes ( like_id character varying(64) NOT NULL, user_id character varying(64) NOT NULL, post_id character varying(64), comment_id character varying(64), created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, PRIMARY KEY (like_id), CONSTRAINT unique_user_like UNIQUE (user_id, post_id, comment_id), CONSTRAINT check_like_target CHECK (post_id IS NOT NULL OR comment_id IS NOT NULL) )
CREATE TABLE social_media.conversations ( conversation_id.text, created_at.timestamp, last_message_at.timestamp, is_group_chat.boolean, group_name.text )
CREATE TABLE social_media.notifications ( notification_id text PRIMARY KEY, recipient_user_id text, sender_user_id text, notification_type text, target_entity_id text, target_entity_type text, created_at timestamp, read_at timestamp )
##Table Structure
CREATE TABLE financial_services.accounts (
    account_id character varying(64) NOT NULL, -- unique identifier for the account
    customer_id character varying(64) NOT NULL, -- foreign key linking to the customer
    account_number character varying(128) NOT NULL UNIQUE, -- unique account number visible to customer
    account_type character varying(50) NOT NULL, -- e.g., Checking, Savings, Investment, Loan, Credit Card
    balance numeric(19, 4) NOT NULL DEFAULT 0.00, -- current account balance
    currency character varying(3) NOT NULL, -- currency code (e.g., USD, EUR)
    opened_date date NOT NULL, -- date the account was opened
    status character varying(32) NOT NULL, -- e.g., Open, Closed, Frozen
    interest_rate numeric(5, 4), -- annual interest rate, if applicable
    last_updated_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, -- timestamp of last account update
    PRIMARY KEY (account_id),
    FOREIGN KEY (customer_id) REFERENCES financial_services.customers(customer_id)
)
##Table Structure
CREATE TABLE gaming_technology.game_sessions ( session_id uuid PRIMARY KEY, player_id uuid, game_id uuid, server_id uuid, start_time timestamptz, end_time timestamptz, duration_seconds int, score int, session_data jsonb )

[User] Find all clients and lawyers who share the same phone area code, and show each client's first and last name, each lawyer's first and last name, and the shared area code.

[Assistant] SELECT c.first_name AS client_first_name, c.last_name AS client_last_name, l.first_name AS lawyer_first_name, l.last_name AS lawyer_last_name, SUBSTRING(c.phone, 1, 3) AS area_code FROM legal_services.clients c JOIN legal_services.lawyers l ON SUBSTRING(c.phone, 1, 3) = SUBSTRING(l.phone, 1, 3);

[User] List pairs of invoices for the same case where one invoice's total_amount is lower than another's; show lower_invoice_number, higher_invoice_number, and case_id.

[Assistant]
SELECT a.invoice_number AS lower_invoice_number,
       b.invoice_number AS higher_invoice_number,
       a.case_id
  FROM legal_services.invoices a
  JOIN legal_services.invoices b
    ON a.case_id = b.case_id
   AND a.total_amount < b.total_amount;

[User] Please only include cases that have at least two invoices and sort by case_id and lower_invoice_number.

[Assistant]
SELECT a.invoice_number AS lower_invoice_number,
       b.invoice_number AS higher_invoice_number,
       a.case_id
  FROM legal_services.invoices a
  JOIN legal_services.invoices b
    ON a.case_id = b.case_id
   AND a.total_amount < b.total_amount
 ORDER BY a.case_id, a.invoice_number;

[User] Show me the latest uploaded document (name and version) for each invoice that is linked to a case, including the invoice number and total amount.

[Assistant]
SELECT i.invoice_number, i.total_amount, d.document_name, d.version AS latest_version
FROM legal_services.invoices i
JOIN legal_services.documents d ON i.case_id = d.case_id
WHERE d.upload_timestamp = (
  SELECT MAX(d2.upload_timestamp)
  FROM legal_services.documents d2
  WHERE d2.case_id = d.case_id
)
AND i.case_id IS NOT NULL;

[User] Find users who have both commented on a post and liked that same post. Return the user_id and the count of such posts as post_count.

[Assistant]
SELECT c.user_id, COUNT(DISTINCT c.post_id) AS post_count
FROM social_media.comments c
JOIN social_media.likes l ON c.user_id = l.user_id
  AND c.post_id = l.post_id
WHERE l.post_id IS NOT NULL
GROUP BY c.user_id;

[User] Additionally, include only those cases where they also liked their own comment on that post. Return user_id, post_id, and comment_id.

[Assistant]
SELECT c.user_id, c.post_id, c.comment_id
FROM social_media.comments c
JOIN social_media.likes l ON c.comment_id = l.comment_id
  AND l.user_id = c.user_id
WHERE l.comment_id IS NOT NULL;

[User] Summarize the accounts table by account type and currency, showing the average balance for each combination.

[Assistant] SELECT account_type, currency, AVG(balance) AS average_balance, COUNT(account_id) AS account_count FROM financial_services.accounts GROUP BY account_type, currency ORDER BY account_type, currency;

[User] Only include combinations where the average balance is greater than 5000.

[Assistant] SELECT account_type, currency, AVG(balance) AS average_balance, COUNT(account_id) AS account_count FROM financial_services.accounts GROUP BY account_type, currency HAVING AVG(balance) > 5000 ORDER BY average_balance DESC;

[User] What's the average session duration for each player for a given server?

[Assistant] SELECT player_id, server_id, AVG(duration_seconds) AS avg_session_duration FROM gaming_technology.game_sessions GROUP BY player_id, server_id;

[User] Only show player-server pairs with more than 2 sessions.

[Assistant] SELECT player_id, server_id, AVG(duration_seconds) AS avg_session_duration, COUNT(*) AS session_count FROM gaming_technology.game_sessions GROUP BY player_id, server_id HAVING COUNT(*) > 2;

[User] Can you add the maximum score that player achieved on each server?

[Assistant] SELECT player_id, server_id, AVG(duration_seconds) AS avg_session_duration, COUNT(*) AS session_count, MAX(score) AS max_score FROM gaming_technology.game_sessions GROUP BY player_id, server_id HAVING COUNT(*) > 2;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement. ##Table Structure
CREATE TABLE financial_services.transactions ( transaction_id text, account_id text, related_account_id text, transaction_type text, amount numeric, currency text, transaction_date timestamp, effective_date date, description text, status text, reference_number text )
CREATE TABLE financial_services.securities ( security_id text, ticker_symbol text, isin_code text, cusip_code text, security_name text, security_type text, exchange text, currency text, issuer_name text, sector text, last_updated timestamp )
CREATE TABLE financial_services.market_data ( data_point_id bigint, security_id text, data_timestamp timestamp, open_price numeric, high_price numeric, low_price numeric, close_price numeric, adjusted_close_price numeric, volume bigint, source text )
##Table Structure
CREATE TABLE gaming_technology.players ( player_id.uuid, username.text, email.text, password_hash.text, registration_date.timestamptz, last_login.timestamptz, country_code.text, status.text, profile_data.jsonb )
##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 financial_services.accounts ( account_id.text, customer_id.text, account_number.text, account_type.text, balance.numeric, currency.text, opened_date.date, status.text, interest_rate.numeric, last_updated_at.timestamp )
##Table Structure
CREATE TABLE social_media.post_hashtags ( post_hashtag_id text, post_id text, hashtag_id text )
CREATE TABLE social_media.conversation_participants ( participant_id text, conversation_id text, user_id text, joined_at timestamp, last_read_at timestamp )
##Table Structure
CREATE TABLE 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) )

[User] Show the total number of transactions for each currency.

[Assistant] SELECT currency, COUNT(*) FROM financial_services.transactions GROUP BY currency

[User] Can you also include the total amount for each currency?

[Assistant] SELECT currency, COUNT(*), SUM(amount) FROM financial_services.transactions GROUP BY currency

[User] Can you give me the count of players grouped by their status?

[Assistant]
SELECT status,
       COUNT(*) AS player_count
FROM gaming_technology.players
GROUP BY status;

[User] Actually, include the percentage of total players for each status.

[Assistant]
SELECT status,
       COUNT(*) AS player_count,
       ROUND(100.0 * COUNT(*) / SUM(COUNT(*)) OVER (), 2) AS percentage
FROM gaming_technology.players
GROUP BY status;

[User] Only show statuses where this percentage is over 10%.

[Assistant]
WITH counts AS (
  SELECT status,
         COUNT(*) AS player_count,
         ROUND(100.0 * COUNT(*) / SUM(COUNT(*)) OVER (), 2) AS percentage
  FROM gaming_technology.players
  GROUP BY status
)
SELECT *
FROM counts
WHERE percentage > 10;

[User] Finally, sort the output by percentage in descending order.

[Assistant]
WITH counts AS (
  SELECT status,
         COUNT(*) AS player_count,
         ROUND(100.0 * COUNT(*) / SUM(COUNT(*)) OVER (), 2) AS percentage
  FROM gaming_technology.players
  GROUP BY status
)
SELECT *
FROM counts
WHERE percentage > 10
ORDER BY percentage DESC;

[User] Show the number of claims filed for each distinct status, ordered by the count in descending order.

[Assistant]
SELECT status, COUNT(*) AS claim_count
FROM insurance.claims
GROUP BY status
ORDER BY claim_count DESC;

[User] Show each customer's checking and savings account numbers for customers who have both types.

[Assistant]
SELECT a.customer_id,
       a.account_number AS checking_account,
       b.account_number AS savings_account
FROM financial_services.accounts a
JOIN financial_services.accounts b
  ON a.customer_id = b.customer_id
  AND a.account_type = 'Checking'
  AND b.account_type = 'Savings';

[User] Also include the opened_date for both checking and savings accounts.

[Assistant]
SELECT a.customer_id,
       a.account_number AS checking_account,
       a.opened_date  AS checking_opened,
       b.account_number AS savings_account,
       b.opened_date  AS savings_opened
FROM financial_services.accounts a
JOIN financial_services.accounts b
  ON a.customer_id = b.customer_id
  AND a.account_type = 'Checking'
  AND b.account_type = 'Savings';

[User] Only include customers where both accounts have status 'Active'.

[Assistant]
SELECT a.customer_id,
       a.account_number AS checking_account,
       a.opened_date  AS checking_opened,
       b.account_number AS savings_account,
       b.opened_date  AS savings_opened
FROM financial_services.accounts a
JOIN financial_services.accounts b
  ON a.customer_id = b.customer_id
  AND a.account_type = 'Checking'
  AND b.account_type = 'Savings'
WHERE a.status = 'Active'
  AND b.status = 'Active';

[User] Show me the user_id and number of conversations they have joined. Only include users who joined more than one conversation.

[Assistant]
SELECT user_id, COUNT(DISTINCT conversation_id) AS conversations_joined
FROM social_media.conversation_participants
GROUP BY user_id
HAVING COUNT(DISTINCT conversation_id) > 1;

[User] Add the time they joined their most recent conversation as latest_joined_at.

[Assistant]
SELECT user_id, COUNT(DISTINCT conversation_id) AS conversations_joined, MAX(joined_at) AS latest_joined_at
FROM social_media.conversation_participants
GROUP BY user_id
HAVING COUNT(DISTINCT conversation_id) > 1;

[User] Also, show the IDs of the conversations for each user as a comma-separated list.

[Assistant]
SELECT user_id,
  COUNT(DISTINCT conversation_id) AS conversations_joined,
  MAX(joined_at) AS latest_joined_at,
  STRING_AGG(DISTINCT conversation_id, ',') AS conversation_ids
FROM social_media.conversation_participants
GROUP BY user_id
HAVING COUNT(DISTINCT conversation_id) > 1;

[User] Which narrative had the highest total USD token inflow during Q1 of 2024, and which chain did these inflows primarily occur on?

[Assistant] SELECT narrative, chain, SUM(usd_value) AS total_inflow FROM smart_money_token_inflow WHERE type = 1 AND EXTRACT(YEAR FROM CURRENT_DATE) = 2024 AND EXTRACT(MONTH FROM CURRENT_DATE) BETWEEN 1 AND 3 GROUP BY narrative, chain ORDER BY total_inflow DESC LIMIT 1;

[User] Could you modify the query to show the top 3 narratives by total inflow, along with their corresponding chains?

[Assistant] SELECT narrative, chain, SUM(usd_value) AS total_inflow FROM smart_money_token_inflow WHERE type = 1 AND EXTRACT(YEAR FROM CURRENT_DATE) = 2024 AND EXTRACT(MONTH FROM CURRENT_DATE) BETWEEN 1 AND 3 GROUP BY narrative, chain ORDER BY total_inflow DESC LIMIT 3;


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 text, first_name text, last_name text, specialty text, license_number text, phone_number text, email text, hospital_affiliation_id text, created_at timestamp, updated_at timestamp )
CREATE TABLE healthcare.appointments ( appointment_id.text, patient_id.text, doctor_id.text, appointment_time.timestamp, duration_minutes.integer, reason.text, status.text, location_id.text, notes.text, created_at.timestamp )
CREATE TABLE healthcare.diagnoses ( diagnosis_id 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.medications (
    medication_id character varying(64) NOT NULL, -- unique identifier for the medication type
    medication_name character varying(255) NOT NULL, -- common or brand name
    generic_name character varying(255), -- generic chemical name
    manufacturer character varying(100), -- drug manufacturer
    ndc_code character varying(20) UNIQUE, -- National Drug Code (optional but useful)
    description text, -- description of the medication
    PRIMARY KEY (medication_id)
)
CREATE TABLE healthcare.prescriptions ( prescription_id text, record_id text, patient_id text, doctor_id text, medication_id text, dosage text, frequency text, route text, start_date date, end_date date, quantity_dispensed numeric, refills_allowed integer, prescription_date timestamp )
CREATE TABLE healthcare.insurance_plans ( plan_id text, plan_name text, insurance_provider text, plan_type text, contact_phone text, website text )
CREATE TABLE healthcare.patient_insurance ( patient_insurance_id text, patient_id text, plan_id text, policy_number text, group_number text, subscriber_name text, effective_date date, expiration_date date, is_primary boolean )
##Table Structure
CREATE TABLE government_services.citizens (
    citizen_id character varying(64) NOT NULL,  -- unique identifier for the citizen
    national_id_number character varying(128) NOT NULL UNIQUE, -- official national identification number
    first_name character varying(100) NOT NULL,
    last_name character varying(100) NOT NULL,
    date_of_birth date NOT NULL,
    gender character varying(20),
    primary_address text NOT NULL, -- full primary residential address
    contact_email character varying(128) UNIQUE,
    contact_phone character varying(32),
    registration_date timestamp NOT NULL, -- when the citizen profile was created
    is_verified boolean DEFAULT false, -- whether identity has been officially verified
    PRIMARY KEY (citizen_id)
)
CREATE TABLE government_services.agencies ( agency_id.text, agency_name.text, jurisdiction_level.text, primary_contact_email.text, main_phone_number.text, website_url.text, established_date.date, parent_agency_id.text )
CREATE TABLE government_services.services ( service_id text PRIMARY KEY, agency_id text, service_name text, description text, category text, eligibility_criteria text, standard_fee numeric, average_processing_time_days int, is_active boolean, online_application_url text )
CREATE TABLE government_services.applications ( application_id character varying(64) NOT NULL, citizen_id character varying(64) NOT NULL, service_id character varying(64) NOT NULL, submitted_at timestamp NOT NULL, status character varying(50) NOT NULL, last_updated_at timestamp NOT NULL, assigned_employee_id character varying(64), decision_date date, notes text, reference_number character varying(100) UNIQUE, PRIMARY KEY (application_id) )
CREATE TABLE government_services.documents ( document_id.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 )
CREATE TABLE government_services.payments ( payment_id text, application_id text, citizen_id text, service_id text, amount numeric, currency text, payment_method text, payment_provider_reference text, payment_timestamp timestamp, status text, notes text )
CREATE TABLE government_services.service_locations (
    location_id character varying(64) NOT NULL, -- unique identifier for the physical location
    agency_id character varying(64) NOT NULL, -- FK to agencies table
    location_name character varying(200), -- e.g., Downtown DMV Office
    address text NOT NULL,
    city character varying(100),
    state character varying(50),
    postal_code character varying(20),
    latitude numeric(9, 6),
    longitude numeric(9, 6),
    operating_hours text, -- description of opening times
    contact_phone character varying(32),
    is_accessible boolean, -- accessibility information (e.g., wheelchair access)
    PRIMARY KEY (location_id)
)
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 trading_platform.dapps (
    dapp_id character varying(64) NOT NULL,  -- unique identifier for the DApp
    name character varying(128) NOT NULL, -- name of the DApp
    description text NOT NULL, -- description of the DApp
    url character varying(256) NOT NULL, -- URL of the DApp
    PRIMARY KEY (dapp_id)
)
CREATE TABLE trading_platform.kyc_audit (
    kyc_audit_id character varying(64) NOT NULL,  -- unique identifier for the KYC audit
    user_id character varying(64) NOT NULL, -- identifier of the user being audited
    status character varying(32) NOT NULL, -- status of the KYC audit (e.g., pending, approved, rejected)
    reviewed_at timestamp NOT NULL, -- time when the KYC audit was reviewed
    PRIMARY KEY (kyc_audit_id)
)

[User] Find all prescriptions for patients who have at least one appointment scheduled in the future. Show the prescription ID, patient ID, medication name, and the earliest future appointment time for that patient.

[Assistant] SELECT pr.prescription_id, pr.patient_id, m.medication_name, ( SELECT MIN(ap.appointment_time) FROM healthcare.appointments AS ap WHERE ap.patient_id = p.patient_id AND ap.appointment_time > CURRENT_TIMESTAMP ) AS earliest_future_appointment_time FROM healthcare.prescriptions AS pr JOIN healthcare.patients AS p ON pr.patient_id = p.patient_id JOIN healthcare.medications AS m ON pr.medication_id = m.medication_id WHERE p.patient_id IN ( SELECT patient_id FROM healthcare.appointments WHERE appointment_time > CURRENT_TIMESTAMP );

[User] Show each service's name along with the total number of appointments scheduled and the number of unique locations these appointments are scheduled at.

[Assistant]
SELECT s.service_name, COUNT(a.application_id) AS appointment_count, COUNT(DISTINCT ap.location_id) AS unique_location_count
FROM government_services.services s
JOIN government_services.applications a ON s.service_id = a.service_id
JOIN government_services.appointments ap ON a.application_id = ap.application_id
GROUP BY s.service_name;

[User] I got an error: relation 'appointments' does not exist.

[Assistant]
-- The appointments table is not present in the provided schema. If you want to count by another join, perhaps by documents or payments, please specify.
-- Alternatively, do you want appointment information replaced with application submissions per service and their associated location from service_locations?
SELECT s.service_name, COUNT(a.application_id) AS application_count, COUNT(DISTINCT sl.location_id) AS unique_location_count
FROM government_services.services s
JOIN government_services.applications a ON s.service_id = a.service_id
JOIN government_services.service_locations sl ON s.agency_id = sl.agency_id
GROUP BY s.service_name;

[User] Show only those services where application_count is greater than 50.

[Assistant]
SELECT s.service_name, COUNT(a.application_id) AS application_count, COUNT(DISTINCT sl.location_id) AS unique_location_count
FROM government_services.services s
JOIN government_services.applications a ON s.service_id = a.service_id
JOIN government_services.service_locations sl ON s.agency_id = sl.agency_id
GROUP BY s.service_name
HAVING COUNT(a.application_id) > 50;

[User] Show me the names and URLs of all DApps, and for each DApp, list the KYC status and last review date for all users who have an audit entry.

[Assistant]
SELECT d.name AS dapp_name, d.url, k.user_id, k.status, k.reviewed_at
FROM trading_platform.dapps d
JOIN trading_platform.kyc_audit k ON 1=1
ORDER BY d.name, k.user_id;

[User] I only want DApps whose name includes the word 'market', and for KYC audits, show only those with status 'approved'.

[Assistant]
SELECT d.name AS dapp_name, d.url, k.user_id, k.status, k.reviewed_at
FROM trading_platform.dapps d
JOIN trading_platform.kyc_audit k ON 1=1
WHERE d.name ILIKE '%market%' AND k.status = 'approved'
ORDER BY d.name, k.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 gaming_technology.achievements ( achievement_id.uuid, game_id.uuid, name.text, description.text, icon_url.text, points.integer, hidden.boolean )
##Table Structure
CREATE TABLE legal_services.lawyers (
    lawyer_id character varying(64) NOT NULL,  -- unique identifier for the lawyer
    first_name character varying(100) NOT NULL, -- lawyer's first name
    last_name character varying(100) NOT NULL, -- lawyer's last name
    bar_number character varying(64) UNIQUE NOT NULL, -- lawyer's bar association number
    firm_id character varying(64), -- FK to law_firms table
    email character varying(128) UNIQUE NOT NULL, -- lawyer's professional email
    phone character varying(32), -- lawyer's contact phone number
    specialization text, -- areas of legal expertise
    hire_date timestamp NOT NULL, -- date the lawyer was hired or joined
    is_partner boolean DEFAULT false, -- flag indicating if the lawyer is a partner
    PRIMARY KEY (lawyer_id)
)
##Table Structure
CREATE TABLE insurance.claims ( claim_id text, policy_id text, customer_id text, incident_date timestamp, reported_date timestamp, description text, estimated_loss numeric, status text, settlement_amount numeric, settlement_date date, claim_handler_id text, police_report_number text )
CREATE TABLE insurance.claim_documents ( document_id text PRIMARY KEY, claim_id text, document_type text, file_name text, file_path text, file_size_bytes int, mime_type text, uploaded_by text, uploaded_at timestamp, description text )
##Table Structure
CREATE TABLE transportation.trips ( trip_id.text, route_id.text, vehicle_id.text, driver_id.text, scheduled_departure.timestamp, actual_departure.timestamp, scheduled_arrival.timestamp, actual_arrival.timestamp, origin_location_id.text, destination_location_id.text, status.text, passenger_count.integer, cargo_manifest_id.text )
##Table Structure
CREATE TABLE government_services.agencies ( agency_id character varying(64) NOT NULL, agency_name character varying(255) NOT NULL, jurisdiction_level character varying(50) NOT NULL, primary_contact_email character varying(128), main_phone_number character varying(32), website_url character varying(255), established_date date, parent_agency_id character varying(64), PRIMARY KEY (agency_id) )
##Table Structure
CREATE TABLE insurance.customers ( customer_id.text, first_name.text, last_name.text, date_of_birth.date, ssn_hash.text, address_line1.text, address_line2.text, city.text, state.text, zip_code.text, country.text, phone_number.text, email.text, created_at.timestamp, updated_at.timestamp, status.text )
##Table Structure
Use Hashes. Key pattern: 'component:<component_id>'. Example: HSET component:LGSTRUT01 part_number "PN-5521-A" component_name "Landing Gear Strut" material_id "mat:TI64" supplier_id "sup:ACME_AERO" ... Consider Sets for reverse lookups (e.g., 'material_components:<material_id>' -> Set<component_id>).
##Table Structure
CREATE TABLE healthcare.insurance_plans ( plan_id text, plan_name text, insurance_provider text, plan_type text, contact_phone text, website text )

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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


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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement. ##Table Structure
CREATE TABLE transportation.vehicles ( vehicle_id character varying(64) NOT NULL, license_plate character varying(32) NOT NULL UNIQUE, vin character varying(17) UNIQUE, make character varying(64) NOT NULL, model character varying(64) NOT NULL, year integer NOT NULL, type character varying(32) NOT NULL, capacity integer, fuel_type character varying(32) NOT NULL, status character varying(32) NOT NULL, depot_id character varying(64), acquisition_date date, PRIMARY KEY (vehicle_id) )
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.fuel_logs ( fuel_log_id.text, vehicle_id.text, trip_id.text, log_timestamp.timestamp, fuel_type.text, quantity.numeric, unit.text, cost_per_unit.numeric, total_cost.numeric, odometer_reading.integer, location_id.text )
CREATE TABLE transportation.passengers ( passenger_id.text, first_name.text, last_name.text, email.text, phone_number.text, date_of_birth.date, loyalty_program_id.text, created_at.timestamp )
##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.likes ( like_id text, user_id text, post_id text, comment_id text, created_at timestamp )
CREATE TABLE social_media.follows ( follow_id character varying(64) NOT NULL, follower_user_id character varying(64) NOT NULL, following_user_id character varying(64) NOT NULL, created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, PRIMARY KEY (follow_id), CONSTRAINT unique_follow UNIQUE (follower_user_id, following_user_id) )
CREATE TABLE social_media.hashtags ( hashtag_id character varying(64) NOT NULL, tag_name character varying(100) NOT NULL UNIQUE, created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, PRIMARY KEY (hashtag_id) )
CREATE TABLE social_media.post_hashtags ( post_hashtag_id character varying(64) NOT NULL, post_id character varying(64) NOT NULL, hashtag_id character varying(64) NOT NULL, PRIMARY KEY (post_hashtag_id), CONSTRAINT unique_post_hashtag UNIQUE (post_id, hashtag_id) )
CREATE TABLE social_media.conversations ( conversation_id text PRIMARY KEY, created_at timestamp, last_message_at timestamp, is_group_chat bool, group_name text )
CREATE TABLE social_media.notifications ( notification_id.text, recipient_user_id.text, sender_user_id.text, notification_type.text, target_entity_id.text, target_entity_type.text, created_at.timestamp, read_at.timestamp )
CREATE TABLE social_media.user_settings ( setting_id text PRIMARY KEY, user_id text, theme text, email_notifications_enabled bool, push_notifications_enabled bool, private_profile bool, updated_at timestamp )
##Table Structure
CREATE TABLE insurance.customers ( customer_id text PRIMARY KEY, first_name text, last_name text, date_of_birth date, ssn_hash text, address_line1 text, address_line2 text, city text, state text, zip_code text, country text, phone_number text, email text, created_at timestamp, updated_at timestamp, status text )
CREATE TABLE insurance.policies ( policy_id text PRIMARY KEY, 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.premium_payments ( payment_id text PRIMARY KEY, policy_id text, customer_id text, payment_date timestamp, amount_paid numeric, payment_method text, transaction_reference text, due_date date, payment_period_start date, payment_period_end date, status text )
CREATE TABLE insurance.claim_documents ( document_id text PRIMARY KEY, claim_id text, document_type text, file_name text, file_path text, file_size_bytes int, mime_type text, uploaded_by text, uploaded_at timestamp, description text )
CREATE TABLE insurance.policy_beneficiaries ( beneficiary_id text PRIMARY KEY, policy_id text, customer_id text, first_name text, last_name text, relationship text, percentage_share numeric, contact_info text, added_at timestamp )
##Table Structure
CREATE TABLE gaming_technology.achievements (
    achievement_id uuid NOT NULL DEFAULT gen_random_uuid(), -- unique identifier for an achievement definition
    game_id uuid NOT NULL, -- FK linking to the game the achievement belongs to
    name character varying(150) NOT NULL, -- name of the achievement
    description text NOT NULL, -- how to unlock the achievement
    icon_url character varying(255), -- URL for the achievement's icon
    points integer DEFAULT 0, -- points awarded for unlocking (optional)
    hidden boolean DEFAULT false, -- whether the achievement details are hidden until unlocked
    PRIMARY KEY (achievement_id)
    -- FOREIGN KEY (game_id) REFERENCES gaming_technology.games(game_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 )

[User] Show me the make and model of vehicles along with the route number and description for routes where the vehicle's capacity is 60 or less.

[Assistant]
SELECT v.make, v.model, r.route_number, r.description
FROM transportation.vehicles v
JOIN transportation.routes r ON v.depot_id IS NOT NULL
WHERE v.capacity <= 60;

[User] Include only the routes where the distance is greater than 100 kilometers, and sort by distance descending.

[Assistant]
SELECT v.make, v.model, r.route_number, r.description, r.distance_km
FROM transportation.vehicles v
JOIN transportation.routes r ON v.depot_id IS NOT NULL
WHERE v.capacity <= 60 AND r.distance_km > 100
ORDER BY r.distance_km DESC;

[User] Which five users have the most followers? Show the following_user_id and the number of followers each has.

[Assistant]
SELECT following_user_id, COUNT(follower_user_id) AS follower_count
FROM social_media.follows
GROUP BY following_user_id
ORDER BY follower_count DESC
LIMIT 5;

[User] List each insurance product's name and type, along with the number of active policies and the total premium_amount collected for those policies. Only include products that have at least one active policy.

[Assistant]
SELECT p.product_name,
       p.product_type,
       COUNT(pl.policy_id) AS active_policy_count,
       SUM(pl.premium_amount) AS total_premium
FROM insurance.insurance_products p
JOIN insurance.policies pl ON p.product_id = pl.product_id
WHERE pl.status = 'Active'
GROUP BY p.product_name, p.product_type
HAVING COUNT(pl.policy_id) > 0;

[User] Can you list the names of achievements and the length of their descriptions? Show the ones with the longest descriptions first.

[Assistant] SELECT name, LENGTH(description) AS description_length FROM achievements ORDER BY description_length DESC LIMIT 10;

[User] For these achievements, can you also show the title of the game they belong to?

[Assistant] SELECT a.name, LENGTH(a.description) AS description_length, g.name AS game_title FROM achievements AS a JOIN games AS g ON a.game_id = g.game_id ORDER BY description_length DESC LIMIT 10;

[User] Also, please only include achievements that are not hidden.

[Assistant] SELECT a.name, LENGTH(a.description) AS description_length, g.name AS game_title FROM achievements AS a JOIN games AS g ON a.game_id = g.game_id WHERE a.hidden = FALSE ORDER BY description_length DESC LIMIT 10;

[User] List pairs of token transfers within the same transaction and for the same token_id where the transfer values are different. Show the transaction ID, token ID, and both transfer IDs and their values.

[Assistant] SELECT t1.transaction_id, t1.token_id, t1.transfer_id AS transfer_id_1, t1.value AS value_1, t2.transfer_id AS transfer_id_2, t2.value AS value_2 FROM web3.token_transfers AS t1 JOIN web3.token_transfers AS t2 ON t1.transaction_id = t2.transaction_id AND t1.token_id = t2.token_id AND t1.transfer_id < t2.transfer_id WHERE t1.value <> t2.value;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement. ##Table Structure
CREATE TABLE social_media.post_hashtags (
    post_hashtag_id character varying(64) NOT NULL, -- unique identifier for the post-hashtag link
    post_id character varying(64) NOT NULL, -- identifier of the post (FK to posts.post_id)
    hashtag_id character varying(64) NOT NULL, -- identifier of the hashtag (FK to hashtags.hashtag_id)
    PRIMARY KEY (post_hashtag_id),
    CONSTRAINT unique_post_hashtag UNIQUE (post_id, hashtag_id) -- prevent duplicate tags on a post
)
CREATE TABLE social_media.conversations ( conversation_id text PRIMARY KEY, created_at timestamp, last_message_at timestamp, is_group_chat bool, group_name 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.token_transfers ( transfer_id.text, token_id.text, from_address.text, to_address.text, value.numeric, transaction_id.text, log_index.integer )
CREATE TABLE web3.wallets ( wallet_id.text, user_id.text, address.text, private_key.text, created_at.timestamp )
CREATE TABLE web3.users ( user_id.text, username.text, email.text, password_hash.text, created_at.timestamp )
##Table Structure
CREATE TABLE healthcare.patients ( patient_id text PRIMARY KEY, first_name text, last_name text, date_of_birth date, gender text, address text, phone_number text, email text, emergency_contact_name text, emergency_contact_phone text, created_at timestamp, updated_at timestamp )
##Table Structure
CREATE TABLE 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.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.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 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 transportation.vehicles ( vehicle_id.text, license_plate.text, vin.text, make.text, model.text, year.integer, type.text, capacity.integer, fuel_type.text, status.text, depot_id.text, acquisition_date.date )
CREATE TABLE transportation.routes ( route_id.text, route_number.text, description.text, origin_location_id.text, destination_location_id.text, distance_km.numeric, estimated_duration_minutes.integer, type.text )
CREATE TABLE transportation.trips ( trip_id.text, route_id.text, vehicle_id.text, driver_id.text, scheduled_departure.timestamp, actual_departure.timestamp, scheduled_arrival.timestamp, actual_arrival.timestamp, origin_location_id.text, destination_location_id.text, status.text, passenger_count.integer, cargo_manifest_id.text )
CREATE TABLE transportation.fuel_logs ( fuel_log_id.text, vehicle_id.text, trip_id.text, log_timestamp.timestamp, fuel_type.text, quantity.numeric, unit.text, cost_per_unit.numeric, total_cost.numeric, odometer_reading.integer, location_id.text )
CREATE TABLE transportation.passengers ( passenger_id.text, first_name.text, last_name.text, email.text, phone_number.text, date_of_birth.date, loyalty_program_id.text, created_at.timestamp )
##Table Structure
CREATE TABLE healthcare.medical_records (
    record_id character varying(64) NOT NULL,  -- unique identifier for the medical record entry
    patient_id character varying(64) NOT NULL, -- FK to patients table
    appointment_id character varying(64) UNIQUE, -- FK to appointments table (can be null if record not tied to specific appt)
    doctor_id character varying(64) NOT NULL, -- FK to doctors table (doctor creating the record)
    record_date timestamp with time zone NOT NULL, -- date the record/observation was made
    chief_complaint text, -- patient's primary reason for visit
    present_illness_history text, -- detailed history of the current issue
    past_medical_history text, -- relevant past conditions/surgeries
    physical_examination_notes text, -- findings from the physical exam
    assessment text, -- doctor's assessment/diagnosis summary
    treatment_plan text, -- planned course of action
    vitals jsonb, -- store vitals like BP, HR, Temp as structured JSON
    created_at timestamp with time zone NOT NULL DEFAULT current_timestamp,
    PRIMARY KEY (record_id)
)
CREATE TABLE healthcare.patient_insurance ( patient_insurance_id text PRIMARY KEY, 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 healthcare.insurance_plans ( plan_id text, plan_name text, insurance_provider text, plan_type text, contact_phone text, website text )

[User] Show me all conversation IDs (whether group chat or not) that have at least one hashtag used in posts linked to them.

[Assistant]
SELECT DISTINCT c.conversation_id
FROM social_media.conversations c
JOIN social_media.post_hashtags ph ON c.conversation_id = ph.post_id;

[User] List the transaction IDs that have both an event and a token transfer, along with the name of the event and the value of the token transfer.

[Assistant] SELECT T1.transaction_id, T1.event_name, T2.value FROM web3.events AS T1 JOIN web3.token_transfers AS T2 ON T1.transaction_id = T2.transaction_id;

[User] List the patient ID, first name, last name, and phone number for all patients whose emergency contact name or phone number is missing.

[Assistant] SELECT patient_id, first_name, last_name, phone_number FROM healthcare.patients WHERE emergency_contact_name IS NULL OR emergency_contact_name = '' OR emergency_contact_phone IS NULL OR emergency_contact_phone = '';

[User] Refine this to also include patients who have a listed email address and sort the results by patient_id.

[Assistant] SELECT patient_id, first_name, last_name, phone_number FROM healthcare.patients WHERE (emergency_contact_name IS NULL OR emergency_contact_name = '' OR emergency_contact_phone IS NULL OR emergency_contact_phone = '') AND email IS NOT NULL AND email != '' ORDER BY patient_id;

[User] Show me the subjects and start times of all appointments along with the document names of any documents uploaded for the associated case.

[Assistant]
SELECT a.subject, a.start_time, d.document_name
FROM legal_services.appointments a
JOIN legal_services.documents d ON a.case_id = d.case_id;

[User] List the full names of all employees who are currently employed (i.e., have no termination date).

[Assistant] SELECT first_name || ' ' || last_name AS full_name FROM government_services.employees WHERE termination_date IS NULL;

[User] List all fuel log entries with their associated trip's route_number and the vehicle's license_plate where the total_cost exceeds 200, sorted by total_cost descending.

[Assistant]
SELECT fl.*, t.route_id, r.route_number, v.license_plate
FROM transportation.fuel_logs fl
JOIN transportation.trips t ON fl.trip_id = t.trip_id
JOIN transportation.routes r ON t.route_id = r.route_id
JOIN transportation.vehicles v ON fl.vehicle_id = v.vehicle_id
WHERE fl.total_cost > 200
ORDER BY fl.total_cost DESC;

[User] For each doctor, count how many medical record entries they have created and show the doctor_id alongside the record count.

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

[User] Find all insurance plans that have both a contact phone number and a website listed, showing their provider and plan type.

[Assistant] SELECT insurance_provider, plan_type FROM healthcare.insurance_plans WHERE contact_phone IS NOT NULL AND 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 transportation.vehicles ( vehicle_id text PRIMARY KEY, license_plate text, vin text, make text, model text, year int, type text, capacity int, fuel_type text, status text, depot_id text, acquisition_date date )
CREATE TABLE transportation.drivers ( driver_id text PRIMARY KEY, employee_id text, first_name text, last_name text, license_number text, license_expiry_date date, contact_number text, email text, hire_date date, status text )
CREATE TABLE transportation.routes ( route_id text PRIMARY KEY, route_number text, description text, origin_location_id text, destination_location_id text, distance_km numeric, estimated_duration_minutes int, type text )
CREATE TABLE transportation.locations ( location_id text PRIMARY KEY, name text, type text, address_line1 text, city text, state_province text, postal_code text, country text, latitude numeric, longitude numeric, timezone text )
CREATE TABLE transportation.maintenance_logs ( log_id text PRIMARY KEY, vehicle_id text, service_date date, odometer_reading int, service_type text, description text, cost numeric, mechanic_name text, next_service_due_date date )
CREATE TABLE transportation.fuel_logs ( fuel_log_id text PRIMARY KEY, vehicle_id text, trip_id text, log_timestamp timestamp, fuel_type text, quantity numeric, unit text, cost_per_unit numeric, total_cost numeric, odometer_reading int, location_id text )
CREATE TABLE transportation.passengers ( passenger_id text PRIMARY KEY, 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 PRIMARY KEY, passenger_id text, trip_id text, seat_number text, booking_time timestamp, status text, fare numeric, payment_transaction_id text, special_requests text )
##Table Structure
CREATE TABLE transportation.vehicles ( vehicle_id text PRIMARY KEY, license_plate text, vin text, make text, model text, year int, type text, capacity int, fuel_type text, status text, depot_id text, acquisition_date date )
CREATE TABLE transportation.drivers ( driver_id.text, employee_id.text, first_name.text, last_name.text, license_number.text, license_expiry_date.date, contact_number.text, email.text, hire_date.date, status.text )
CREATE TABLE transportation.routes ( route_id text, route_number text, description text, origin_location_id text, destination_location_id text, distance_km numeric, estimated_duration_minutes integer, type text )
CREATE TABLE transportation.locations ( location_id text, name text, type text, address_line1 text, city text, state_province text, postal_code text, country text, latitude numeric, longitude numeric, timezone text )
CREATE TABLE transportation.maintenance_logs (
    log_id character varying(64) NOT NULL,  -- unique identifier for the maintenance record
    vehicle_id character varying(64) NOT NULL, -- identifier of the vehicle serviced
    service_date date NOT NULL, -- date the service was performed
    odometer_reading integer, -- vehicle mileage at time of service
    service_type character varying(128) NOT NULL, -- type of service (e.g., Oil Change, Tire Rotation, Engine Repair)
    description text NOT NULL, -- detailed description of work done
    cost numeric(10, 2), -- cost of the service
    mechanic_name character varying(128), -- name or ID of the mechanic/shop
    next_service_due_date date, -- recommended date for next service
    PRIMARY KEY (log_id)
)
CREATE TABLE transportation.passengers (
    passenger_id character varying(64) NOT NULL,  -- unique identifier for the passenger
    first_name character varying(128) NOT NULL, -- passenger's first name
    last_name character varying(128) NOT NULL, -- passenger's last name
    email character varying(128) UNIQUE, -- email address
    phone_number character varying(32) UNIQUE, -- phone number
    date_of_birth date, -- passenger's date of birth
    loyalty_program_id character varying(64), -- identifier for loyalty program membership
    created_at timestamp with time zone NOT NULL, -- time when the passenger record was created
    PRIMARY KEY (passenger_id)
)
CREATE TABLE transportation.bookings ( booking_id character varying(64) NOT NULL, passenger_id character varying(64) NOT NULL, trip_id character varying(64) NOT NULL, seat_number character varying(16), booking_time timestamp with time zone NOT NULL, status character varying(32) NOT NULL, fare numeric(10, 2) NOT NULL, payment_transaction_id character varying(128), special_requests text, PRIMARY KEY (booking_id) )
##Table Structure
CREATE TABLE 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.policy_beneficiaries (
    beneficiary_id character varying(64) NOT NULL, -- unique identifier for the beneficiary entry
    policy_id character varying(64) NOT NULL, -- identifier of the life/relevant policy (FK to policies)
    customer_id character varying(64) NOT NULL, -- identifier of the beneficiary (could be FK to customers or store info directly)
    first_name character varying(100) NOT NULL, -- beneficiary first name (if not linking to customers table)
    last_name character varying(100) NOT NULL, -- beneficiary last name
    relationship character varying(50) NOT NULL, -- relationship to the policyholder (e.g., Spouse, Child, Parent)
    percentage_share numeric(5, 2) NOT NULL CHECK (percentage_share > 0 AND percentage_share <= 100), -- percentage of payout
    contact_info text, -- contact details for the beneficiary
    added_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
    PRIMARY KEY (beneficiary_id),
    UNIQUE (policy_id, customer_id) -- Ensure a person is listed only once per policy
)
##Table Structure
CREATE TABLE social_media.post_hashtags ( post_hashtag_id character varying(64) NOT NULL, post_id character varying(64) NOT NULL, hashtag_id character varying(64) NOT NULL, PRIMARY KEY (post_hashtag_id), CONSTRAINT unique_post_hashtag UNIQUE (post_id, hashtag_id) )

[User] Show the full name and email of each driver and the number of vehicles currently assigned to their depot.

[Assistant]
SELECT d.first_name, d.last_name, d.email, COUNT(v.vehicle_id) AS vehicles_at_depot
FROM transportation.drivers d
JOIN transportation.vehicles v ON d.driver_id = v.vehicle_id
JOIN transportation.locations l ON v.depot_id = l.location_id
GROUP BY d.driver_id, d.first_name, d.last_name, d.email;

[User] I think the join is incorrect—drivers don’t have vehicle_id. Can you instead count all vehicles per depot and show each driver's full name, email, and the count for their assigned depot, assuming drivers and vehicles share depot assignments by depot_id?

[Assistant]
SELECT d.first_name, d.last_name, d.email, COUNT(v.vehicle_id) AS vehicles_at_depot
FROM transportation.drivers d
JOIN transportation.vehicles v ON d.status = 'Active' AND d.driver_id IS NOT NULL AND v.depot_id = (
    SELECT v2.depot_id FROM transportation.vehicles v2 WHERE v2.vehicle_id = v.vehicle_id LIMIT 1
)
GROUP BY d.driver_id, d.first_name, d.last_name, d.email;

[User] List all drivers along with the make and model of each vehicle they have been assigned to for trips.

[Assistant]
SELECT DISTINCT d.driver_id, d.first_name || ' ' || d.last_name AS driver_full_name, v.make, v.model
FROM transportation.drivers d
JOIN transportation.trips t ON d.driver_id = t.driver_id
JOIN transportation.vehicles v ON t.vehicle_id = v.vehicle_id;

[User] What is the average estimated_loss for each claim status?

[Assistant]
SELECT status, AVG(estimated_loss) AS avg_estimated_loss
FROM insurance.claims
GROUP BY status;

[User] How many unique hashtags are linked to each post? Return post_id and hashtag_count.

[Assistant]
SELECT post_id, COUNT(DISTINCT hashtag_id) AS hashtag_count
FROM social_media.post_hashtags
GROUP BY post_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 )
##Table Structure
CREATE TABLE government_services.employees (
    employee_id character varying(64) NOT NULL, -- unique identifier for the government employee
    agency_id character varying(64) NOT NULL, -- FK to agencies table
    first_name character varying(100) NOT NULL,
    last_name character varying(100) NOT NULL,
    job_title character varying(150) NOT NULL,
    department character varying(100),
    work_email character varying(128) NOT NULL UNIQUE,
    work_phone character varying(32),
    hire_date date NOT NULL,
    termination_date date, -- null if currently employed
    access_level character varying(50), -- Role or permission level
    manager_employee_id character varying(64), -- FK to self for reporting structure
    PRIMARY KEY (employee_id)
)
##Table Structure
CREATE TABLE healthcare.doctors ( doctor_id text, first_name text, last_name text, specialty text, license_number text, phone_number text, email text, hospital_affiliation_id text, created_at timestamp, updated_at timestamp )
CREATE TABLE healthcare.diagnoses (
    diagnosis_id character varying(64) NOT NULL, -- unique identifier for the diagnosis entry
    record_id character varying(64) NOT NULL, -- FK linking to the specific medical record entry
    patient_id character varying(64) NOT NULL, -- FK to patients table
    doctor_id character varying(64) NOT NULL, -- FK to doctors table (diagnosing doctor)
    diagnosis_code character varying(20) NOT NULL, -- standard code (e.g., ICD-10)
    code_type character varying(10) NOT NULL DEFAULT 'ICD-10', -- type of code used
    description text, -- textual description of the diagnosis
    diagnosis_date date NOT NULL, -- date the diagnosis was made
    status character varying(32) NOT NULL, -- e.g., Active, Resolved, Ruled Out
    is_chronic boolean DEFAULT false, -- flag for chronic conditions
    PRIMARY KEY (diagnosis_id)
)
CREATE TABLE healthcare.insurance_plans ( plan_id text, plan_name text, insurance_provider text, plan_type text, contact_phone text, website text )
##Table Structure
CREATE TABLE trading_platform.users ( user_id character varying(64) NOT NULL, username character varying(128) NOT NULL, email character varying(128) NOT NULL, password_hash text NOT NULL, created_at timestamp NOT NULL, PRIMARY KEY (user_id) )
CREATE TABLE trading_platform.wallets ( wallet_id character varying(64) NOT NULL, user_id character varying(64) NOT NULL, address character varying(128) NOT NULL, private_key text NOT NULL, created_at timestamp NOT NULL, PRIMARY KEY (wallet_id) )
CREATE TABLE trading_platform.orders ( order_id character varying(64) NOT NULL, user_id character varying(64) NOT NULL, wallet_id character varying(64) NOT NULL, asset_id character varying(64) NOT NULL, order_type character varying(32) NOT NULL, quantity numeric(38,14) NOT NULL, price numeric(38,14) NOT NULL, status character varying(32) NOT NULL, created_at timestamp NOT NULL, PRIMARY KEY (order_id) )
CREATE TABLE trading_platform.utxos ( utxo_id character varying(64) NOT NULL, transaction_id character varying(64) NOT NULL, output_index integer NOT NULL, address character varying(128) NOT NULL, amount numeric(38,14) NOT NULL, spent boolean NOT NULL, PRIMARY KEY (utxo_id) )
CREATE TABLE trading_platform.dapps ( dapp_id character varying(64) NOT NULL, name character varying(128) NOT NULL, description text NOT NULL, url character varying(256) NOT NULL, PRIMARY KEY (dapp_id) )
CREATE TABLE trading_platform.metadata ( metadata_id character varying(64) NOT NULL, asset_id character varying(64) NOT NULL, key character varying(128) NOT NULL, value text NOT NULL, PRIMARY KEY (metadata_id) )
CREATE TABLE trading_platform.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) )
CREATE TABLE trading_platform.notifications ( notification_id character varying(64) NOT NULL, user_id character varying(64) NOT NULL, message text NOT NULL, sent_at timestamp NOT NULL, read_at timestamp, PRIMARY KEY (notification_id) )
##Table Structure
CREATE TABLE social_media.messages ( message_id.text, conversation_id.text, sender_user_id.text, content.text, media_url.text, media_type.text, sent_at.timestamp, read_at.timestamp )
CREATE TABLE social_media.notifications ( notification_id text, recipient_user_id text, sender_user_id text, notification_type text, target_entity_id text, target_entity_type text, created_at timestamp, read_at timestamp )
##Table Structure
CREATE TABLE gaming_technology.game_sessions ( session_id uuid PRIMARY KEY, player_id uuid, game_id uuid, server_id uuid, start_time timestamptz, end_time timestamptz, duration_seconds int, score int, session_data jsonb )
##Table Structure
CREATE TABLE transportation.routes ( route_id text PRIMARY KEY, route_number text, description text, origin_location_id text, destination_location_id text, distance_km numeric, estimated_duration_minutes int, type text )

[User] Retrieve the first and last names and email addresses of all customers who registered after '2024-01-01'.

[Assistant] SELECT first_name, last_name, email FROM insurance.customers WHERE created_at > '2024-01-01';

[User] List all distinct job titles present in the organization.

[Assistant] SELECT DISTINCT job_title FROM government_services.employees;

[User] For each doctor, count the number of chronic diagnoses they have made. Show the doctor's full name and the count.

[Assistant] SELECT doc.first_name, doc.last_name, COUNT(d.diagnosis_id) FROM healthcare.doctors doc JOIN healthcare.diagnoses d ON doc.doctor_id = d.doctor_id WHERE d.is_chronic = TRUE GROUP BY doc.doctor_id, doc.first_name, doc.last_name ORDER BY COUNT(d.diagnosis_id) DESC;

[User] Show each wallet address and the number of canceled orders it has, ordering the results by that count in descending order.

[Assistant]
SELECT w.address,
       COUNT(o.order_id) AS canceled_orders
FROM trading_platform.wallets w
LEFT JOIN trading_platform.orders o
  ON w.wallet_id = o.wallet_id
  AND o.status = 'canceled'
GROUP BY w.address
ORDER BY canceled_orders DESC;

[User] List all messages that haven’t triggered any notification; show message_id, sender_user_id, and sent_at.

[Assistant]
SELECT m.message_id, m.sender_user_id, m.sent_at
FROM social_media.messages AS m
LEFT JOIN social_media.notifications AS n
  ON n.target_entity_type = 'message'
  AND n.target_entity_id = m.message_id
WHERE n.notification_id IS NULL;

[User] Actually, only include those sent before '2024-06-01'.

[Assistant]
SELECT m.message_id, m.sender_user_id, m.sent_at
FROM social_media.messages AS m
LEFT JOIN social_media.notifications AS n
  ON n.target_entity_type = 'message'
  AND n.target_entity_id = m.message_id
WHERE n.notification_id IS NULL
  AND m.sent_at < '2024-06-01';

[User] For each server, what is the earliest and latest start time of its sessions?

[Assistant] SELECT server_id, MIN(start_time), MAX(start_time) FROM gaming_technology.game_sessions GROUP BY server_id;

[User] Only show servers where the difference between the earliest and latest session is more than 30 days.

[Assistant] SELECT server_id, MIN(start_time), MAX(start_time) FROM gaming_technology.game_sessions GROUP BY server_id HAVING MAX(start_time) - MIN(start_time) > INTERVAL '30 days';

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

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

[User] Now filter to include only route types with average duration greater than 60 minutes and order by average duration descending.

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


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement. ##Table Structure
CREATE TABLE healthcare.insurance_plans ( plan_id text PRIMARY KEY, plan_name text, insurance_provider text, plan_type text, contact_phone text, website text )
##Table Structure
CREATE TABLE social_media.messages (
    message_id character varying(64) NOT NULL, -- unique identifier for the message
    conversation_id character varying(64) NOT NULL, -- identifier for the conversation thread (FK to conversations.conversation_id)
    sender_user_id character varying(64) NOT NULL, -- identifier of the sender (FK to users.user_id)
    content text, -- textual content of the message
    media_url text, -- URL to attached media (image/video)
    media_type character varying(20), -- type of media ('image', 'video', null)
    sent_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, -- timestamp when message was sent
    read_at timestamp, -- timestamp when message was read by recipient(s)
    PRIMARY KEY (message_id)
)
##Table Structure
CREATE TABLE government_services.service_locations ( location_id.text, agency_id.text, location_name.text, address.text, city.text, state.text, postal_code.text, latitude.numeric, longitude.numeric, operating_hours.text, contact_phone.text, is_accessible.boolean )
##Table Structure
CREATE TABLE healthcare.patient_insurance ( patient_insurance_id.text, patient_id.text, plan_id.text, policy_number.text, group_number.text, subscriber_name.text, effective_date.date, expiration_date.date, is_primary.boolean )
##Table Structure
CREATE TABLE transportation.vehicles ( vehicle_id text PRIMARY KEY, license_plate text, vin text, make text, model text, year int, type text, capacity int, fuel_type text, status text, depot_id text, acquisition_date date )
##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 healthcare.doctors ( doctor_id text, first_name text, last_name text, specialty text, license_number text, phone_number text, email text, hospital_affiliation_id text, created_at timestamp, updated_at timestamp )
##Table Structure
CREATE TABLE trading_platform.users ( user_id.text, username.text, email.text, password_hash.text, created_at.timestamp )
CREATE TABLE trading_platform.orders ( order_id.text, user_id.text, wallet_id.text, asset_id.text, order_type.text, quantity.numeric, price.numeric, status.text, created_at.timestamp )
CREATE TABLE trading_platform.dapps ( dapp_id.text, name.text, description.text, url.text )
CREATE TABLE trading_platform.logs ( log_id.text, user_id.text, action.text, details.text, logged_at.timestamp )
##Table Structure
CREATE TABLE government_services.applications ( application_id text PRIMARY KEY, citizen_id text, service_id text, submitted_at timestamp, status text, last_updated_at timestamp, assigned_employee_id text, decision_date date, notes text, reference_number text )
##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 insurance.policies ( policy_id.text, customer_id.text, product_id.text, agent_id.text, policy_number.text, start_date.date, end_date.date, premium_amount.numeric, coverage_limit.numeric, deductible.numeric, status.text, issued_at.timestamp, cancellation_date.date, cancellation_reason.text )
##Table Structure
CREATE TABLE social_media.posts ( post_id text, user_id text, content text, media_url text, media_type text, created_at timestamp, updated_at timestamp, visibility text, location_lat numeric, location_lon numeric )
CREATE TABLE social_media.likes ( like_id text, user_id text, post_id text, comment_id text, created_at timestamp )
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] Provide each pair of plans that share the same plan_type but are offered by different providers.

[Assistant]
SELECT p1.plan_type,
       p1.plan_id AS plan1_id,
       p1.plan_name AS plan1_name,
       p1.insurance_provider AS provider1,
       p2.plan_id AS plan2_id,
       p2.plan_name AS plan2_name,
       p2.insurance_provider AS provider2
FROM healthcare.insurance_plans p1
JOIN healthcare.insurance_plans p2
  ON p1.plan_type = p2.plan_type
 AND p1.insurance_provider < p2.insurance_provider;

[User] List message IDs and their sent time for messages containing media attachments.

[Assistant] SELECT message_id ,  sent_at FROM social_media.messages WHERE media_type IS NOT NULL

[User] How many service locations are accessible in each state? Provide the state and the count of accessible locations.

[Assistant] SELECT state, COUNT(*) FROM government_services.service_locations WHERE is_accessible = TRUE GROUP BY state;

[User] Count how many insurance policies have an effective date in the year 2023.

[Assistant] SELECT COUNT(*) FROM healthcare.patient_insurance WHERE EXTRACT(YEAR FROM effective_date) = 2023;

[User] I need a list of pairs of vehicles that share the same type but have different fuel_types, showing both vehicle IDs and their fuel types.

[Assistant]
SELECT v1.vehicle_id,
       v1.fuel_type,
       v2.vehicle_id AS other_vehicle_id,
       v2.fuel_type AS other_fuel_type
FROM transportation.vehicles v1
JOIN transportation.vehicles v2
  ON v1.type = v2.type
 AND v1.fuel_type <> v2.fuel_type
 AND v1.vehicle_id < v2.vehicle_id;

[User] For each transaction, find the next transaction initiated by the same sender. List the original transaction_id, the next transaction_id, the sender address, and the time difference in hours between them.

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

[User] Count the total number of distinct specialties listed in the doctors table.

[Assistant] SELECT count(DISTINCT specialty) FROM healthcare.doctors;

[User] List the names and URLs of all decentralized applications where the description includes the word 'exchange'.

[Assistant]
SELECT d.name, d.url
FROM trading_platform.dapps d
WHERE d.description ILIKE '%exchange%';

[User] For each service ID, what is the average number of days between the submission date and the decision date for applications that have a recorded decision?

[Assistant] SELECT service_id, AVG(EXTRACT(EPOCH FROM (decision_date - submitted_at)) / 86400) AS average_days_to_decision FROM government_services.applications WHERE decision_date IS NOT NULL GROUP BY service_id;

[User] For each recipient address, count how many token transfers they have received.

[Assistant] SELECT to_address, COUNT(*) AS received_transfer_count FROM web3.token_transfers GROUP BY to_address;

[User] Only show addresses that have received more than 100 transfers.

[Assistant] SELECT to_address, COUNT(*) AS received_transfer_count FROM web3.token_transfers GROUP BY to_address HAVING COUNT(*) > 100;

[User] List pairs of policies for the same customer where one policy starts exactly one day after another policy ends. Return customer_id, the earlier policy_number, the later policy_number, earlier end_date, and later start_date.

[Assistant]
SELECT p1.customer_id,
       p1.policy_number AS earlier_policy,
       p2.policy_number AS later_policy,
       p1.end_date,
       p2.start_date
FROM insurance.policies p1
JOIN insurance.policies p2
  ON p1.customer_id = p2.customer_id
 AND p2.start_date = p1.end_date + INTERVAL '1 day';

[User] How many group chats have been created since January 1, 2024?

[Assistant]
SELECT COUNT(*) AS group_chat_count
FROM social_media.conversations
WHERE is_group_chat = TRUE
  AND created_at >= '2024-01-01';