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.servers ( server_id uuid, game_id uuid, server_name text, region text, ip_address text, port integer, current_players integer, max_players integer, status text, last_heartbeat timestamp with time zone )

[User] For each game_id and region, show me the server that currently has the highest current_players and the server that has the highest max_players. Return game_id, region, top_current_server_id, top_current_players, top_capacity_server_id, and top_capacity.

[Assistant]
WITH top_current AS (
  SELECT
    s1.game_id,
    s1.region,
    s1.server_id AS top_current_server_id,
    s1.current_players AS top_current_players
  FROM gaming_technology.servers s1
  WHERE NOT EXISTS (
    SELECT 1
    FROM gaming_technology.servers s2
    WHERE s2.game_id = s1.game_id
      AND s2.region = s1.region
      AND s2.current_players > s1.current_players
  )
),
top_capacity AS (
  SELECT
    s3.game_id,
    s3.region,
    s3.server_id AS top_capacity_server_id,
    s3.max_players AS top_capacity
  FROM gaming_technology.servers s3
  WHERE NOT EXISTS (
    SELECT 1
    FROM gaming_technology.servers s4
    WHERE s4.game_id = s3.game_id
      AND s4.region = s3.region
      AND s4.max_players > s3.max_players
  )
)
SELECT
  tc.game_id,
  tc.region,
  tc.top_current_server_id,
  tc.top_current_players,
  cp.top_capacity_server_id,
  cp.top_capacity
FROM top_current tc
JOIN top_capacity cp
  ON tc.game_id = cp.game_id
  AND tc.region = cp.region;

[User] Actually, can you also calculate the difference between top_capacity and top_current_players as free_slots_diff?

[Assistant]
WITH top_current AS (
  SELECT
    s1.game_id,
    s1.region,
    s1.server_id AS top_current_server_id,
    s1.current_players AS top_current_players
  FROM gaming_technology.servers s1
  WHERE NOT EXISTS (
    SELECT 1
    FROM gaming_technology.servers s2
    WHERE s2.game_id = s1.game_id
      AND s2.region = s1.region
      AND s2.current_players > s1.current_players
  )
),
top_capacity AS (
  SELECT
    s3.game_id,
    s3.region,
    s3.server_id AS top_capacity_server_id,
    s3.max_players AS top_capacity
  FROM gaming_technology.servers s3
  WHERE NOT EXISTS (
    SELECT 1
    FROM gaming_technology.servers s4
    WHERE s4.game_id = s3.game_id
      AND s4.region = s3.region
      AND s4.max_players > s3.max_players
  )
)
SELECT
  tc.game_id,
  tc.region,
  tc.top_current_server_id,
  tc.top_current_players,
  cp.top_capacity_server_id,
  cp.top_capacity,
  (cp.top_capacity - tc.top_current_players) AS free_slots_diff
FROM top_current tc
JOIN top_capacity cp
  ON tc.game_id = cp.game_id
  AND tc.region = cp.region;

[User] Now only include combinations where free_slots_diff is less than 10.

[Assistant]
WITH top_current AS (
  SELECT
    s1.game_id,
    s1.region,
    s1.server_id AS top_current_server_id,
    s1.current_players AS top_current_players
  FROM gaming_technology.servers s1
  WHERE NOT EXISTS (
    SELECT 1
    FROM gaming_technology.servers s2
    WHERE s2.game_id = s1.game_id
      AND s2.region = s1.region
      AND s2.current_players > s1.current_players
  )
),
top_capacity AS (
  SELECT
    s3.game_id,
    s3.region,
    s3.server_id AS top_capacity_server_id,
    s3.max_players AS top_capacity
  FROM gaming_technology.servers s3
  WHERE NOT EXISTS (
    SELECT 1
    FROM gaming_technology.servers s4
    WHERE s4.game_id = s3.game_id
      AND s4.region = s3.region
      AND s4.max_players > s3.max_players
  )
)
SELECT
  tc.game_id,
  tc.region,
  tc.top_current_server_id,
  tc.top_current_players,
  cp.top_capacity_server_id,
  cp.top_capacity,
  (cp.top_capacity - tc.top_current_players) AS free_slots_diff
FROM top_current tc
JOIN top_capacity cp
  ON tc.game_id = cp.game_id
  AND tc.region = cp.region
WHERE (cp.top_capacity - tc.top_current_players) < 10;

[User] Also, filter to only include servers with status = 'online'.

[Assistant]
WITH top_current AS (
  SELECT
    s1.game_id,
    s1.region,
    s1.server_id AS top_current_server_id,
    s1.current_players AS top_current_players
  FROM gaming_technology.servers s1
  WHERE s1.status = 'online'
    AND NOT EXISTS (
      SELECT 1
      FROM gaming_technology.servers s2
      WHERE s2.game_id = s1.game_id
        AND s2.region = s1.region
        AND s2.current_players > s1.current_players
    )
),
top_capacity AS (
  SELECT
    s3.game_id,
    s3.region,
    s3.server_id AS top_capacity_server_id,
    s3.max_players AS top_capacity
  FROM gaming_technology.servers s3
  WHERE s3.status = 'online'
    AND NOT EXISTS (
      SELECT 1
      FROM gaming_technology.servers s4
      WHERE s4.game_id = s3.game_id
        AND s4.region = s3.region
        AND s4.max_players > s3.max_players
    )
)
SELECT
  tc.game_id,
  tc.region,
  tc.top_current_server_id,
  tc.top_current_players,
  cp.top_capacity_server_id,
  cp.top_capacity,
  (cp.top_capacity - tc.top_current_players) AS free_slots_diff
FROM top_current tc
JOIN top_capacity cp
  ON tc.game_id = cp.game_id
  AND tc.region = cp.region
WHERE (cp.top_capacity - tc.top_current_players) < 10;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE financial_services.customers ( customer_id text PRIMARY KEY, first_name text, last_name text, date_of_birth date, ssn_hash text, address text, city text, state text, zip_code text, country text, email text, phone_number text, created_at timestamp, status text, risk_profile text )
CREATE TABLE financial_services.employees ( employee_id text PRIMARY KEY, first_name text, last_name text, job_title text, department text, branch_id text, email text, phone_extension text, hire_date date, termination_date date, manager_id text, status text )

[User] For each employee, show their full name, their manager's full name, and the number of days between their hire dates.

[Assistant]
SELECT e.employee_id,
       e.first_name || ' ' || e.last_name AS employee_name,
       m.employee_id AS manager_id,
       m.first_name || ' ' || m.last_name AS manager_name,
       DATE_PART('day', e.hire_date - m.hire_date) AS days_difference
FROM financial_services.employees e
JOIN financial_services.employees m
  ON e.manager_id = m.employee_id;

[User] Actually, only include cases where the employee was hired after their manager.

[Assistant]
SELECT e.employee_id,
       e.first_name || ' ' || e.last_name AS employee_name,
       m.employee_id AS manager_id,
       m.first_name || ' ' || m.last_name AS manager_name,
       DATE_PART('day', e.hire_date - m.hire_date) AS days_difference
FROM financial_services.employees e
JOIN financial_services.employees m
  ON e.manager_id = m.employee_id
WHERE e.hire_date > m.hire_date;

[User] Also, exclude employees who don't have a manager assigned.

[Assistant]
SELECT e.employee_id,
       e.first_name || ' ' || e.last_name AS employee_name,
       m.employee_id AS manager_id,
       m.first_name || ' ' || m.last_name AS manager_name,
       DATE_PART('day', e.hire_date - m.hire_date) AS days_difference
FROM financial_services.employees e
JOIN financial_services.employees m
  ON e.manager_id = m.employee_id
WHERE e.manager_id IS NOT NULL
  AND e.hire_date > m.hire_date;

[User] Finally, order the result by the days_difference descending and limit to 5.

[Assistant]
SELECT e.employee_id,
       e.first_name || ' ' || e.last_name AS employee_name,
       m.employee_id AS manager_id,
       m.first_name || ' ' || m.last_name AS manager_name,
       DATE_PART('day', e.hire_date - m.hire_date) AS days_difference
FROM financial_services.employees e
JOIN financial_services.employees m
  ON e.manager_id = m.employee_id
WHERE e.manager_id IS NOT NULL
  AND e.hire_date > m.hire_date
ORDER BY days_difference DESC
LIMIT 5;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE hospitality_technology.properties ( property_id character varying(64) NOT NULL, property_name character varying(255) NOT NULL, address_line1 character varying(255) NOT NULL, address_line2 character varying(255), city character varying(100) NOT NULL, state_province character varying(100), postal_code character varying(20) NOT NULL, country_code character varying(3) NOT NULL, phone_number character varying(30), email_address character varying(255), property_type character varying(50) NOT NULL, star_rating numeric(2,1), timezone character varying(64) NOT NULL, manager_staff_id character varying(64), created_at timestamp with time zone NOT NULL DEFAULT current_timestamp, updated_at timestamp with time zone NOT NULL DEFAULT current_timestamp, PRIMARY KEY (property_id) )
CREATE TABLE hospitality_technology.reservations ( reservation_id character varying(64) NOT NULL, property_id character varying(64) NOT NULL, guest_id character varying(64) NOT NULL, room_id character varying(64), room_type_id character varying(64) NOT NULL, check_in_date date NOT NULL, check_out_date date NOT NULL, actual_check_in_ts timestamp with time zone, actual_check_out_ts timestamp with time zone, num_adults integer NOT NULL, num_children integer DEFAULT 0, status character varying(50) NOT NULL, booking_source character varying(100), rate_plan_id character varying(64), total_amount numeric(12, 2), amount_paid numeric(12, 2) DEFAULT 0.00, special_requests text, created_at timestamp with time zone NOT NULL DEFAULT current_timestamp, updated_at timestamp with time zone NOT NULL DEFAULT current_timestamp, PRIMARY KEY (reservation_id), FOREIGN KEY (property_id) REFERENCES hospitality_technology.properties(property_id), FOREIGN KEY (guest_id) REFERENCES hospitality_technology.guests(guest_id), FOREIGN KEY (room_id) REFERENCES hospitality_technology.rooms(room_id), FOREIGN KEY (room_type_id) REFERENCES hospitality_technology.room_types(room_type_id) )
CREATE TABLE hospitality_technology.staff ( staff_id text PRIMARY KEY, 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 int, manager_id text, created_at timestamp )
CREATE TABLE hospitality_technology.services ( service_id character varying(64) NOT NULL, property_id character varying(64) NOT NULL, service_name character varying(150) NOT NULL, description text, category character varying(100), price numeric(10, 2) NOT NULL, unit character varying(30), is_available boolean NOT NULL DEFAULT true, department character varying(100), PRIMARY KEY (service_id), FOREIGN KEY (property_id) REFERENCES hospitality_technology.properties(property_id) )
CREATE TABLE hospitality_technology.service_orders ( order_id text PRIMARY KEY, reservation_id text, guest_id text, service_id text, staff_id_ordered text, staff_id_delivered text, order_timestamp timestamp, delivery_timestamp timestamp, quantity int, unit_price numeric, total_price numeric, status text, notes text, bill_id text )

[User] List each property along with the total revenue generated from all delivered service orders, including the property name and total revenue.

[Assistant]
SELECT p.property_id, p.property_name, SUM(so.total_price) AS total_revenue
FROM hospitality_technology.properties p
JOIN hospitality_technology.services s ON s.property_id = p.property_id
JOIN hospitality_technology.service_orders so ON so.service_id = s.service_id
WHERE so.status = 'delivered'
GROUP BY p.property_id, p.property_name;


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 PRIMARY KEY, first_name text, last_name text, company_name text, email text UNIQUE, phone text, address text, date_registered timestamp, status text )
CREATE TABLE legal_services.lawyers ( lawyer_id.text, first_name.text, last_name.text, bar_number.text, firm_id.text, email.text, phone.text, specialization.text, hire_date.timestamp, is_partner.boolean )
CREATE TABLE legal_services.cases (
    case_id character varying(64) NOT NULL,  -- unique identifier for the case/matter
    case_number character varying(100) UNIQUE, -- official case number (court or internal)
    case_name text NOT NULL, -- descriptive name or title for the case
    client_id character varying(64) NOT NULL, -- FK to clients table
    lead_lawyer_id character varying(64) NOT NULL, -- FK to lawyers table (primary lawyer responsible)
    case_type character varying(100) NOT NULL, -- e.g., Litigation, Corporate, Family Law, IP
    status character varying(50) NOT NULL, -- e.g., Open, Closed, Pending, On Hold, Appealed
    date_opened timestamp NOT NULL, -- date the case was formally opened
    date_closed timestamp, -- date the case was closed (nullable)
    description text, -- detailed description of the case
    court_jurisdiction character varying(128), -- court or jurisdiction if applicable
    PRIMARY KEY (case_id)
)
CREATE TABLE legal_services.invoices ( invoice_id text, invoice_number text, client_id text, case_id text, issue_date date, due_date date, total_amount numeric, amount_paid numeric, status text, payment_date timestamp, notes text, created_at timestamp )

[User] List each partner lawyer's first_name, last_name along with the count of invoices for the cases they lead.

[Assistant]
SELECT l.lawyer_id, l.first_name, l.last_name, COUNT(i.invoice_id) AS invoice_count
FROM legal_services.lawyers l
JOIN legal_services.cases c ON l.lawyer_id = c.lead_lawyer_id
JOIN legal_services.invoices i ON c.case_id = i.case_id
WHERE l.is_partner = TRUE
GROUP BY l.lawyer_id, l.first_name, l.last_name;

[User] Only include those partners who have more than 3 invoices.

[Assistant]
SELECT l.lawyer_id, l.first_name, l.last_name, COUNT(i.invoice_id) AS invoice_count
FROM legal_services.lawyers l
JOIN legal_services.cases c ON l.lawyer_id = c.lead_lawyer_id
JOIN legal_services.invoices i ON c.case_id = i.case_id
WHERE l.is_partner = TRUE
GROUP BY l.lawyer_id, l.first_name, l.last_name
HAVING COUNT(i.invoice_id) > 3;

[User] Also restrict to invoices issued after '2024-01-01'.

[Assistant]
SELECT l.lawyer_id, l.first_name, l.last_name, COUNT(i.invoice_id) AS invoice_count
FROM legal_services.lawyers l
JOIN legal_services.cases c ON l.lawyer_id = c.lead_lawyer_id
JOIN legal_services.invoices i ON c.case_id = i.case_id
WHERE l.is_partner = TRUE
  AND i.issue_date > '2024-01-01'
GROUP BY l.lawyer_id, l.first_name, l.last_name
HAVING COUNT(i.invoice_id) > 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 financial_services.accounts ( account_id character varying(64) NOT NULL, customer_id character varying(64) NOT NULL, account_number character varying(128) NOT NULL UNIQUE, account_type character varying(50) NOT NULL, balance numeric(19, 4) NOT NULL DEFAULT 0.00, currency character varying(3) NOT NULL, opened_date date NOT NULL, status character varying(32) NOT NULL, interest_rate numeric(5, 4), last_updated_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, PRIMARY KEY (account_id), FOREIGN KEY (customer_id) REFERENCES financial_services.customers(customer_id) )
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) )
CREATE TABLE financial_services.employees ( employee_id character varying(64) NOT NULL, first_name character varying(100) NOT NULL, last_name character varying(100) NOT NULL, job_title character varying(100) NOT NULL, department character varying(100), branch_id character varying(64), email character varying(128) NOT NULL UNIQUE, phone_extension character varying(20), hire_date date NOT NULL, termination_date date, manager_id character varying(64), status character varying(32) NOT NULL, PRIMARY KEY (employee_id), FOREIGN KEY (branch_id) REFERENCES financial_services.branches(branch_id), FOREIGN KEY (manager_id) REFERENCES financial_services.employees(employee_id) )
CREATE TABLE financial_services.loans ( loan_id character varying(64) NOT NULL, account_id character varying(64) NOT NULL UNIQUE, loan_type character varying(50) NOT NULL, principal_amount numeric(19, 4) NOT NULL, current_principal_balance numeric(19, 4) NOT NULL, interest_rate numeric(6, 4) NOT NULL, term_months integer NOT NULL, origination_date date NOT NULL, maturity_date date NOT NULL, monthly_payment numeric(12, 4), collateral_description text, status character varying(32) NOT NULL, PRIMARY KEY (loan_id), FOREIGN KEY (account_id) REFERENCES financial_services.accounts(account_id) )

[User] Show me each account along with any loans linked to it. Include the account type, account balance, loan type, and loan principal amount.

[Assistant] SELECT a.account_type, a.balance, l.loan_type, l.principal_amount FROM financial_services.accounts a JOIN financial_services.loans l ON a.account_id = l.account_id

[User] Only include loans that are currently 'Active'.

[Assistant] SELECT a.account_type, a.balance, l.loan_type, l.principal_amount FROM financial_services.accounts a JOIN financial_services.loans l ON a.account_id = l.account_id WHERE l.status = 'Active'

[User] Now, summarize this data by account type, showing the total balance of accounts with active loans and the total principal amount of those active loans.

[Assistant] SELECT a.account_type, SUM(a.balance) AS total_account_balance, SUM(l.principal_amount) AS total_active_loan_principal FROM financial_services.accounts a JOIN financial_services.loans l ON a.account_id = l.account_id WHERE l.status = 'Active' GROUP BY a.account_type


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE web3.contracts ( contract_id text, address text, abi text, bytecode text, deployer_address text, deployed_at timestamp, network_id text, status text )
CREATE TABLE web3.events ( event_id text, contract_id text, event_name text, data text, emitted_at timestamp, transaction_id text, log_index integer )
CREATE TABLE web3.transactions ( transaction_id text, from_address text, to_address text, value numeric, gas_used integer, gas_price numeric, block_number integer, timestamp timestamp, input_data text, status text, nonce integer )
CREATE TABLE web3.tokens ( token_id text, contract_address text, token_name text, token_symbol text, decimals integer, total_supply numeric )
CREATE TABLE web3.token_transfers ( transfer_id text, token_id text, from_address text, to_address text, value numeric, transaction_id text, log_index integer )
CREATE TABLE web3.users ( user_id text, username text, email text, password_hash text, created_at timestamp )

[User] List all transactions together with any event emitted in the same transaction, showing transaction ID, event name, and event emitted timestamp.

[Assistant]
SELECT tx.transaction_id, ev.event_name, ev.emitted_at
FROM web3.transactions tx
LEFT JOIN web3.events ev ON tx.transaction_id = ev.transaction_id
ORDER BY tx.transaction_id, ev.log_index;

[User] Only show transactions that have at least one event emitted, and include the contract address that emitted the event.

[Assistant]
SELECT tx.transaction_id, ev.event_name, ev.emitted_at, c.address AS contract_address
FROM web3.transactions tx
JOIN web3.events ev ON tx.transaction_id = ev.transaction_id
JOIN web3.contracts c ON ev.contract_id = c.contract_id
ORDER BY tx.transaction_id, ev.log_index;


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.patients (
    patient_id character varying(64) NOT NULL,  -- unique identifier for the patient
    first_name character varying(100) NOT NULL, -- patient's first name
    last_name character varying(100) NOT NULL, -- patient's last name
    date_of_birth date NOT NULL, -- patient's date of birth
    gender character varying(10), -- patient's gender (e.g., Male, Female, Other)
    address text, -- patient's home address
    phone_number character varying(20), -- patient's phone number
    email character varying(128) UNIQUE, -- patient's email address
    emergency_contact_name character varying(200), -- name of emergency contact
    emergency_contact_phone character varying(20), -- phone number of emergency contact
    created_at timestamp with time zone NOT NULL DEFAULT current_timestamp, -- record creation time
    updated_at timestamp with time zone NOT NULL DEFAULT current_timestamp, -- record last update time
    PRIMARY KEY (patient_id)
)
CREATE TABLE healthcare.appointments (
    appointment_id character varying(64) NOT NULL, -- unique identifier for the appointment
    patient_id character varying(64) NOT NULL, -- FK to patients table
    doctor_id character varying(64) NOT NULL, -- FK to doctors table
    appointment_time timestamp with time zone NOT NULL, -- date and time of the appointment
    duration_minutes integer NOT NULL, -- expected duration in minutes
    reason text, -- reason for the visit
    status character varying(32) NOT NULL, -- e.g., Scheduled, Completed, Cancelled, No-show
    location_id character varying(64), -- FK to a potential locations/clinics table
    notes text, -- notes related to scheduling
    created_at timestamp with time zone NOT NULL DEFAULT current_timestamp,
    PRIMARY KEY (appointment_id)
)
CREATE TABLE healthcare.medications ( medication_id text PRIMARY KEY, medication_name text, generic_name text, manufacturer text, ndc_code text, description text )
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 character varying(64) NOT NULL, -- unique identifier for this patient-plan link
    patient_id character varying(64) NOT NULL, -- FK to patients table
    plan_id character varying(64) NOT NULL, -- FK to insurance_plans table
    policy_number character varying(100) NOT NULL, -- patient's policy number
    group_number character varying(100), -- group number, if applicable
    subscriber_name character varying(200), -- name of the primary policy holder
    effective_date date NOT NULL, -- date the coverage begins
    expiration_date date, -- date the coverage ends (if known)
    is_primary boolean NOT NULL DEFAULT true, -- indicates if this is the primary insurance
    PRIMARY KEY (patient_insurance_id),
    UNIQUE (patient_id, plan_id, policy_number) -- ensure a patient doesn't have the same policy twice
)

[User] Show all patients along with the names of all insurance plans they are enrolled in, plus the insurance provider for each plan.

[Assistant]
SELECT p.patient_id, p.first_name, p.last_name, ip.plan_name, ip.insurance_provider
FROM healthcare.patients p
JOIN healthcare.patient_insurance pi ON p.patient_id = pi.patient_id
JOIN healthcare.insurance_plans ip ON pi.plan_id = ip.plan_id;

[User] Only include patients whose insurance plan type is 'POS'.

[Assistant]
SELECT p.patient_id, p.first_name, p.last_name, ip.plan_name, ip.insurance_provider
FROM healthcare.patients p
JOIN healthcare.patient_insurance pi ON p.patient_id = pi.patient_id
JOIN healthcare.insurance_plans ip ON pi.plan_id = ip.plan_id
WHERE ip.plan_type = 'POS';

[User] Also, sort the results by patient's last name in ascending order and insurance plan name descending.

[Assistant]
SELECT p.patient_id, p.first_name, p.last_name, ip.plan_name, ip.insurance_provider
FROM healthcare.patients p
JOIN healthcare.patient_insurance pi ON p.patient_id = pi.patient_id
JOIN healthcare.insurance_plans ip ON pi.plan_id = ip.plan_id
WHERE ip.plan_type = 'POS'
ORDER BY p.last_name ASC, ip.plan_name 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 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 )

[User] List each passenger's first_name, last_name along with another passenger's first_name and last_name who share the same loyalty_program_id. Label them as member and peer.

[Assistant]
SELECT p1.first_name AS member_first, p1.last_name AS member_last,
       p2.first_name AS peer_first, p2.last_name AS peer_last
FROM transportation.passengers p1
JOIN transportation.passengers p2
  ON p1.loyalty_program_id = p2.loyalty_program_id
  AND p1.passenger_id <> p2.passenger_id;

[User] I only want pairs where the member registered before the peer and include their created_at timestamps.

[Assistant]
SELECT p1.first_name AS member_first, p1.last_name AS member_last,
       p2.first_name AS peer_first, p2.last_name AS peer_last,
       p1.created_at AS member_created, p2.created_at AS peer_created
FROM transportation.passengers p1
JOIN transportation.passengers p2
  ON p1.loyalty_program_id = p2.loyalty_program_id
  AND p1.passenger_id <> p2.passenger_id
  AND p1.created_at < p2.created_at;

[User] Then sort the result by member_created ascending and peer_created descending.

[Assistant]
SELECT p1.first_name AS member_first, p1.last_name AS member_last,
       p2.first_name AS peer_first, p2.last_name AS peer_last,
       p1.created_at AS member_created, p2.created_at AS peer_created
FROM transportation.passengers p1
JOIN transportation.passengers p2
  ON p1.loyalty_program_id = p2.loyalty_program_id
  AND p1.passenger_id <> p2.passenger_id
  AND p1.created_at < p2.created_at
ORDER BY p1.created_at ASC, p2.created_at 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 trading_platform.wallets ( wallet_id.text, user_id.text, address.text, private_key.text, created_at.timestamp )
CREATE TABLE trading_platform.dapps ( dapp_id.text, name.text, description.text, url.text )
CREATE TABLE trading_platform.kyc_audit ( kyc_audit_id.text, user_id.text, status.text, reviewed_at.timestamp )
CREATE TABLE trading_platform.logs ( log_id.text, user_id.text, action.text, details.text, logged_at.timestamp )

[User] Show all users who have no wallets yet.

[Assistant]
SELECT DISTINCT k.user_id
FROM trading_platform.kyc_audit k
LEFT JOIN trading_platform.wallets w ON k.user_id = w.user_id
WHERE w.wallet_id IS NULL;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE healthcare.patients (
    patient_id character varying(64) NOT NULL,  -- unique identifier for the patient
    first_name character varying(100) NOT NULL, -- patient's first name
    last_name character varying(100) NOT NULL, -- patient's last name
    date_of_birth date NOT NULL, -- patient's date of birth
    gender character varying(10), -- patient's gender (e.g., Male, Female, Other)
    address text, -- patient's home address
    phone_number character varying(20), -- patient's phone number
    email character varying(128) UNIQUE, -- patient's email address
    emergency_contact_name character varying(200), -- name of emergency contact
    emergency_contact_phone character varying(20), -- phone number of emergency contact
    created_at timestamp with time zone NOT NULL DEFAULT current_timestamp, -- record creation time
    updated_at timestamp with time zone NOT NULL DEFAULT current_timestamp, -- record last update time
    PRIMARY KEY (patient_id)
)
CREATE TABLE healthcare.doctors ( doctor_id text PRIMARY KEY, 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, record_id character varying(64) NOT NULL, patient_id character varying(64) NOT NULL, doctor_id character varying(64) NOT NULL, diagnosis_code character varying(20) NOT NULL, code_type character varying(10) NOT NULL DEFAULT 'ICD-10', description text, diagnosis_date date NOT NULL, status character varying(32) NOT NULL, is_chronic boolean DEFAULT false, PRIMARY KEY (diagnosis_id) )
CREATE TABLE healthcare.prescriptions ( prescription_id text, record_id text, patient_id text, doctor_id text, medication_id text, dosage text, frequency text, route text, start_date date, end_date date, quantity_dispensed numeric, refills_allowed integer, prescription_date timestamp )
CREATE TABLE healthcare.patient_insurance (
    patient_insurance_id character varying(64) NOT NULL, -- unique identifier for this patient-plan link
    patient_id character varying(64) NOT NULL, -- FK to patients table
    plan_id character varying(64) NOT NULL, -- FK to insurance_plans table
    policy_number character varying(100) NOT NULL, -- patient's policy number
    group_number character varying(100), -- group number, if applicable
    subscriber_name character varying(200), -- name of the primary policy holder
    effective_date date NOT NULL, -- date the coverage begins
    expiration_date date, -- date the coverage ends (if known)
    is_primary boolean NOT NULL DEFAULT true, -- indicates if this is the primary insurance
    PRIMARY KEY (patient_insurance_id),
    UNIQUE (patient_id, plan_id, policy_number) -- ensure a patient doesn't have the same policy twice
)

[User] I need to list patients' full names along with the description and date of their most recent chronic diagnosis, including the diagnosing doctor's full name.

[Assistant] SELECT p.first_name || ' ' || p.last_name AS patient_name, d.description, d.diagnosis_date, doc.first_name || ' ' || doc.last_name AS doctor_name FROM healthcare.diagnoses d JOIN healthcare.patients p ON p.patient_id = d.patient_id JOIN healthcare.doctors doc ON doc.doctor_id = d.doctor_id WHERE d.is_chronic = true AND d.diagnosis_date = (SELECT MAX(d2.diagnosis_date) FROM healthcare.diagnoses d2 WHERE d2.patient_id = d.patient_id AND d2.is_chronic = true);

[User] Actually, only include diagnoses with status 'Active'.

[Assistant] SELECT p.first_name || ' ' || p.last_name AS patient_name, d.description, d.diagnosis_date, doc.first_name || ' ' || doc.last_name AS doctor_name FROM healthcare.diagnoses d JOIN healthcare.patients p ON p.patient_id = d.patient_id JOIN healthcare.doctors doc ON doc.doctor_id = d.doctor_id WHERE d.is_chronic = true AND d.status = 'Active' AND d.diagnosis_date = (SELECT MAX(d2.diagnosis_date) FROM healthcare.diagnoses d2 WHERE d2.patient_id = d.patient_id AND d2.is_chronic = true AND d2.status = 'Active');

[User] And sort by diagnosis_date descending and limit to the top 20.

[Assistant] SELECT p.first_name || ' ' || p.last_name AS patient_name, d.description, d.diagnosis_date, doc.first_name || ' ' || doc.last_name AS doctor_name FROM healthcare.diagnoses d JOIN healthcare.patients p ON p.patient_id = d.patient_id JOIN healthcare.doctors doc ON doc.doctor_id = d.doctor_id WHERE d.is_chronic = true AND d.status = 'Active' AND d.diagnosis_date = (SELECT MAX(d2.diagnosis_date) FROM healthcare.diagnoses d2 WHERE d2.patient_id = d.patient_id AND d2.is_chronic = true AND d2.status = 'Active') ORDER BY d.diagnosis_date DESC LIMIT 20;


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.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 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, passenger_id.text, trip_id.text, seat_number.text, booking_time.timestamp, status.text, fare.numeric, payment_transaction_id.text, special_requests.text )

[User] Which vehicles have been refueled more than 3 times in the last 30 days? Provide the vehicle_id, make, model, and refuel_count.

[Assistant]
SELECT v.vehicle_id,
       v.make,
       v.model,
       COUNT(fl.fuel_log_id) AS refuel_count
FROM transportation.vehicles v
JOIN transportation.fuel_logs fl
  ON v.vehicle_id = fl.vehicle_id
WHERE fl.log_timestamp >= NOW() - INTERVAL '30 days'
GROUP BY v.vehicle_id, v.make, v.model
HAVING COUNT(fl.fuel_log_id) > 3;

[User] Now, only include refuels where fuel_type = 'Diesel' and order by refuel_count DESC.

[Assistant]
SELECT v.vehicle_id,
       v.make,
       v.model,
       COUNT(fl.fuel_log_id) AS refuel_count
FROM transportation.vehicles v
JOIN transportation.fuel_logs fl
  ON v.vehicle_id = fl.vehicle_id
WHERE fl.log_timestamp >= NOW() - INTERVAL '30 days'
  AND fl.fuel_type = 'Diesel'
GROUP BY v.vehicle_id, v.make, v.model
HAVING COUNT(fl.fuel_log_id) > 3
ORDER BY refuel_count DESC;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE healthcare.patients (
    patient_id character varying(64) NOT NULL,  -- unique identifier for the patient
    first_name character varying(100) NOT NULL, -- patient's first name
    last_name character varying(100) NOT NULL, -- patient's last name
    date_of_birth date NOT NULL, -- patient's date of birth
    gender character varying(10), -- patient's gender (e.g., Male, Female, Other)
    address text, -- patient's home address
    phone_number character varying(20), -- patient's phone number
    email character varying(128) UNIQUE, -- patient's email address
    emergency_contact_name character varying(200), -- name of emergency contact
    emergency_contact_phone character varying(20), -- phone number of emergency contact
    created_at timestamp with time zone NOT NULL DEFAULT current_timestamp, -- record creation time
    updated_at timestamp with time zone NOT NULL DEFAULT current_timestamp, -- record last update time
    PRIMARY KEY (patient_id)
)
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.patient_insurance (
    patient_insurance_id character varying(64) NOT NULL, -- unique identifier for this patient-plan link
    patient_id character varying(64) NOT NULL, -- FK to patients table
    plan_id character varying(64) NOT NULL, -- FK to insurance_plans table
    policy_number character varying(100) NOT NULL, -- patient's policy number
    group_number character varying(100), -- group number, if applicable
    subscriber_name character varying(200), -- name of the primary policy holder
    effective_date date NOT NULL, -- date the coverage begins
    expiration_date date, -- date the coverage ends (if known)
    is_primary boolean NOT NULL DEFAULT true, -- indicates if this is the primary insurance
    PRIMARY KEY (patient_insurance_id),
    UNIQUE (patient_id, plan_id, policy_number) -- ensure a patient doesn't have the same policy twice
)

[User] List the names and manufacturers of all medications that do not have an NDC code.

[Assistant]
SELECT medication_name, manufacturer
FROM healthcare.medications
WHERE ndc_code IS NULL;

[User] Please also show the description for each medication.

[Assistant]
SELECT medication_name, manufacturer, description
FROM healthcare.medications
WHERE ndc_code IS NULL;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE web3.contracts ( contract_id character varying(64) NOT NULL, address character varying(128) NOT NULL, abi text NOT NULL, bytecode text NOT NULL, deployer_address character varying(128) NOT NULL, deployed_at timestamp NOT NULL, network_id character varying(64) NOT NULL, status character varying(32) NOT NULL, PRIMARY KEY (contract_id) )
CREATE TABLE web3.transactions ( transaction_id character varying(64) NOT NULL, from_address character varying(128) NOT NULL, to_address character varying(128), value numeric(38,14) NOT NULL, gas_used integer NOT NULL, gas_price numeric(38,14) NOT NULL, block_number integer NOT NULL, timestamp timestamp NOT NULL, input_data text, status character varying(32) NOT NULL, nonce integer NOT NULL, PRIMARY KEY (transaction_id) )
CREATE TABLE web3.users ( user_id text, username text, email text, password_hash text, created_at timestamp )

[User] List the usernames and registration dates for users who registered before the earliest deployed contract.

[Assistant] SELECT T1.username, T1.created_at FROM web3.users AS T1 JOIN (SELECT MIN(deployed_at) AS earliest_deploy FROM web3.contracts) AS T2 ON T1.created_at < T2.earliest_deploy;


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.user_settings ( setting_id text, user_id text, theme text, email_notifications_enabled boolean, push_notifications_enabled boolean, private_profile boolean, updated_at timestamp )

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

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


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 character varying(64) NOT NULL, property_id character varying(64) NOT NULL, room_number character varying(10) NOT NULL, room_type_id character varying(64) NOT NULL, floor integer, status character varying(50) NOT NULL, is_smoking boolean NOT NULL DEFAULT false, features text, current_condition text, last_cleaned_at timestamp with time zone, PRIMARY KEY (room_id), FOREIGN KEY (property_id) REFERENCES hospitality_technology.properties(property_id), FOREIGN KEY (room_type_id) REFERENCES hospitality_technology.room_types(room_type_id) )
CREATE TABLE hospitality_technology.staff ( staff_id character varying(64) NOT NULL, property_id character varying(64) NOT NULL, first_name character varying(100) NOT NULL, last_name character varying(100) NOT NULL, position character varying(100) NOT NULL, work_email character varying(255) UNIQUE, work_phone character varying(30), hire_date date NOT NULL, termination_date date, is_active boolean NOT NULL DEFAULT true, access_level integer NOT NULL, manager_id character varying(64), created_at timestamp with time zone NOT NULL DEFAULT current_timestamp, PRIMARY KEY (staff_id), FOREIGN KEY (property_id) REFERENCES hospitality_technology.properties(property_id), FOREIGN KEY (manager_id) REFERENCES hospitality_technology.staff(staff_id) )
CREATE TABLE hospitality_technology.services ( service_id character varying(64) NOT NULL, property_id character varying(64) NOT NULL, service_name character varying(150) NOT NULL, description text, category character varying(100), price numeric(10, 2) NOT NULL, unit character varying(30), is_available boolean NOT NULL DEFAULT true, department character varying(100), PRIMARY KEY (service_id), FOREIGN KEY (property_id) REFERENCES hospitality_technology.properties(property_id) )
CREATE TABLE hospitality_technology.service_orders ( order_id character varying(64) NOT NULL, reservation_id character varying(64), guest_id character varying(64) NOT NULL, service_id character varying(64) NOT NULL, staff_id_ordered character varying(64), staff_id_delivered character varying(64), order_timestamp timestamp with time zone NOT NULL DEFAULT current_timestamp, delivery_timestamp timestamp with time zone, quantity integer NOT NULL DEFAULT 1, unit_price numeric(10, 2) NOT NULL, total_price numeric(12, 2) NOT NULL, status character varying(50) NOT NULL, notes text, bill_id character varying(64), PRIMARY KEY (order_id), FOREIGN KEY (reservation_id) REFERENCES hospitality_technology.reservations(reservation_id), FOREIGN KEY (guest_id) REFERENCES hospitality_technology.guests(guest_id), FOREIGN KEY (service_id) REFERENCES hospitality_technology.services(service_id), FOREIGN KEY (staff_id_ordered) REFERENCES hospitality_technology.staff(staff_id), FOREIGN KEY (staff_id_delivered) REFERENCES hospitality_technology.staff(staff_id) )

[User] Show me each staff member and the count of service orders they have delivered.

[Assistant]
SELECT st.staff_id, st.first_name, st.last_name, COUNT(so.order_id) AS delivered_orders
FROM hospitality_technology.staff st
LEFT JOIN hospitality_technology.service_orders so ON st.staff_id = so.staff_id_delivered
GROUP BY st.staff_id, st.first_name, st.last_name;

[User] I only want those delivered in the last 7 days.

[Assistant]
SELECT st.staff_id, st.first_name, st.last_name, COUNT(so.order_id) AS delivered_orders_last_week
FROM hospitality_technology.staff st
LEFT JOIN hospitality_technology.service_orders so
  ON st.staff_id = so.staff_id_delivered
  AND so.delivery_timestamp >= NOW() - INTERVAL '7 days'
GROUP BY st.staff_id, st.first_name, st.last_name;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE token_metas ( block_timestamp timestamp, block_number bigint, transaction_hash text, transaction_index bigint, from_address text, contract_address text, symbol text, total_supply text, name text, decimals bigint, is_erc20 integer, is_erc721 integer, is_erc1155 integer, is_proxy integer, extra_info text, pk integer )
CREATE TABLE erc1155_approval_for_all ( block_number bigint, block_timestamp timestamp, transaction_index integer, transaction_hash text, log_index integer, contract_address text )
CREATE TABLE erc20_balances_historical ( block_number bigint, contract_address text, wallet_address text, amount text, pk integer )
CREATE TABLE nft_holders ( block_number bigint, contract_address text, wallet_address text, token_id text, contract_type text, amount text, pk text )
CREATE TABLE nft_holder_historical ( block_number bigint, contract_address text, wallet_address text, token_id text, contract_type text, amount text, pk integer )
CREATE TABLE sui_coins ( object_id text, status text, coin_type text, balance text, owner text )
CREATE TABLE sui_coins_metadata ( object_id text, coin_type text, status text, decimals bigint, description text, icon_url text, symbol text, name text )
CREATE TABLE sui_nfts ( object_id text, status text, collection_type text, package_id text, previous_transaction text, display text, owner text, name text )
CREATE TABLE nft_metadata ( blockchain text, contract_address text, token_id text, contract_name text, erc_type text, amount bigint, minter text, owner text, mint_block_number bigint, mint_time bigint, mint_transaction_hash text, mint_price text, token_uri text, metadata text, name text, image_uri text, traits text, updated_at bigint, status text, rarity_score real, rarity_rank integer, unique_attribute_count integer, pk integer )
CREATE TABLE nft_collections ( blockchain text, contract_address text, name text, symbol text, deploy_block_number bigint, deploy_block_time bigint, erc_type text, owner text, traits text, description text, slug text, media_info text, image_url text, banner_image_url text, updated_at bigint, banner text, token_count bigint, floor_price text, floor_price_symbol text, floor_price_contract text, pk integer )
CREATE TABLE token_prices ( uuid text, blockchain text, address text, decimals bigint, symbol text, price real, timestamp timestamp )
CREATE TABLE token_prices_latest ( blockchain text, address text, decimals bigint, symbol text, price real, timestamp timestamp )
CREATE TABLE erc20_approval ( block_number bigint, block_timestamp timestamp, transaction_index integer, transaction_hash text, log_index integer, contract_address text, pk integer )
CREATE TABLE token_balances ( block_number bigint, block_timestamp timestamp, tick text, wallet_address text, total_supply decimal, amount decimal )
CREATE TABLE token_info ( block_timestamp timestamp, block_number bigint, tx_index integer, tx_hash text, tick text, max_supply decimal, lim decimal, wlim decimal, dec integer, creator text )
CREATE TABLE token_activities ( block_timestamp timestamp, block_number bigint, tx_index integer, tx_hash text, log_index integer, type text, tick text, id text, amt decimal, from_address text, to_address text )
CREATE TABLE mud_holesky_redstone ( address text, table_id text, key_bytes text, key0 text, key1 text, static_data text, encoded_lengths text, dynamic_data text, is_deleted boolean, block_number bigint, log_index bigint )
CREATE TABLE token_balances_bitcoin ( block_number bigint, block_timestamp timestamp, tick text, wallet_address text, total_supply text, amount text )
CREATE TABLE token_info_bitcoin ( block_timestamp timestamp, block_number bigint, tx_index integer, tx_hash text, tick text, max_supply decimal, lim decimal, wlim decimal, dec integer, creator text )
CREATE TABLE token_activities_bitcoin ( block_timestamp timestamp, block_number bigint, tx_index integer, tx_hash text, log_index integer, type text, tick text, id text, amt decimal, from_address text, to_address text )
CREATE TABLE token_activities_avalanche ( block_timestamp timestamp, block_number bigint, tx_index integer, tx_hash text, log_index integer, type text, tick text, id text, amt decimal, from_address text, to_address text )
CREATE TABLE token_balances_avalanche ( block_number bigint, block_timestamp timestamp, tick text, wallet_address text, total_supply decimal, amount decimal )
CREATE TABLE token_info_avalanche ( block_timestamp timestamp, block_number bigint, tx_index integer, tx_hash text, tick text, max_supply decimal, lim decimal, wlim decimal, dec integer, creator text, minted decimal, holders decimal, txs decimal, updated_timestamp timestamp, completed_timestamp timestamp, id text )

[User] Get all active SUI coins with their owner and balance.

[Assistant]
SELECT coin_type, owner, balance
FROM sui_coins
WHERE status = 'active';

[User] Join metadata to include the coin symbol and decimals.

[Assistant]
SELECT c.coin_type,
       m.symbol,
       m.decimals,
       c.owner,
       c.balance
FROM sui_coins c
JOIN sui_coins_metadata m
  ON c.coin_type = m.coin_type
WHERE c.status = 'active';

[User] Only include coins where balance is greater than 500 and add the description.

[Assistant]
SELECT c.coin_type,
       m.symbol,
       m.decimals,
       m.description,
       c.owner,
       c.balance
FROM sui_coins c
JOIN sui_coins_metadata m
  ON c.coin_type = m.coin_type
WHERE c.status = 'active'
  AND CAST(c.balance AS numeric) > 500;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE insurance.policies ( policy_id text 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 )

[User] Find customers who have at least two policies with overlapping coverage periods. Show customer_id, policy1_id, policy2_id, overlap_start and overlap_end.

[Assistant]
SELECT p1.customer_id,
       p1.policy_id AS policy1_id,
       p2.policy_id AS policy2_id,
       GREATEST(p1.start_date, p2.start_date) AS overlap_start,
       LEAST(p1.end_date, p2.end_date) AS overlap_end
FROM insurance.policies p1
JOIN insurance.policies p2
  ON p1.customer_id = p2.customer_id
 AND p1.policy_id < p2.policy_id
 AND p1.start_date <= p2.end_date
 AND p2.start_date <= p1.end_date;

[User] Now only include cases where both policies are active.

[Assistant]
SELECT p1.customer_id,
       p1.policy_id AS policy1_id,
       p2.policy_id AS policy2_id,
       GREATEST(p1.start_date, p2.start_date) AS overlap_start,
       LEAST(p1.end_date, p2.end_date) AS overlap_end
FROM insurance.policies p1
JOIN insurance.policies p2
  ON p1.customer_id = p2.customer_id
 AND p1.policy_id < p2.policy_id
 AND p1.start_date <= p2.end_date
 AND p2.start_date <= p1.end_date
WHERE p1.status = 'active'
  AND p2.status = 'active';

[User] Also restrict to overlaps where overlap duration is more than 30 days and order by overlap duration descending.

[Assistant]
SELECT p1.customer_id,
       p1.policy_id AS policy1_id,
       p2.policy_id AS policy2_id,
       GREATEST(p1.start_date, p2.start_date) AS overlap_start,
       LEAST(p1.end_date, p2.end_date) AS overlap_end,
       EXTRACT(DAY FROM (LEAST(p1.end_date, p2.end_date) - GREATEST(p1.start_date, p2.start_date))) AS overlap_duration
FROM insurance.policies p1
JOIN insurance.policies p2
  ON p1.customer_id = p2.customer_id
 AND p1.policy_id < p2.policy_id
 AND p1.start_date <= p2.end_date
 AND p2.start_date <= p1.end_date
WHERE p1.status = 'active'
  AND p2.status = 'active'
  AND EXTRACT(DAY FROM (LEAST(p1.end_date, p2.end_date) - GREATEST(p1.start_date, p2.start_date))) > 30
ORDER BY overlap_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 transportation.trips (
    trip_id character varying(64) NOT NULL,  -- unique identifier for a specific trip instance
    route_id character varying(64), -- identifier of the route being followed (can be null for ad-hoc trips)
    vehicle_id character varying(64) NOT NULL, -- identifier of the vehicle used
    driver_id character varying(64) NOT NULL, -- identifier of the driver operating
    scheduled_departure timestamp with time zone NOT NULL, -- planned departure time
    actual_departure timestamp with time zone, -- actual departure time
    scheduled_arrival timestamp with time zone NOT NULL, -- planned arrival time
    actual_arrival timestamp with time zone, -- actual arrival time
    origin_location_id character varying(64) NOT NULL, -- actual starting location (could differ from route origin)
    destination_location_id character varying(64) NOT NULL, -- actual ending location (could differ from route destination)
    status character varying(32) NOT NULL, -- e.g., Scheduled, In Progress, Completed, Delayed, Cancelled
    passenger_count integer, -- number of passengers (if applicable)
    cargo_manifest_id character varying(64), -- link to cargo details (if applicable)
    PRIMARY KEY (trip_id)
)

[User] Find pairs of trip IDs where both trips departed on the same calendar day, shared the same origin and destination locations, but were distinct trips.

[Assistant]
SELECT
  t1.trip_id AS trip_id_1,
  t2.trip_id AS trip_id_2,
  t1.origin_location_id,
  t1.destination_location_id,
  DATE(t1.scheduled_departure) AS departure_date
FROM transportation.trips AS t1
JOIN transportation.trips AS t2
  ON t1.origin_location_id = t2.origin_location_id
  AND t1.destination_location_id = t2.destination_location_id
  AND DATE(t1.scheduled_departure) = DATE(t2.scheduled_departure)
  AND t1.trip_id < t2.trip_id;

[User] From those pairs, filter the results to only include pairs where the actual departure times were within 2 hours of each other.

[Assistant]
SELECT
  t1.trip_id AS trip_id_1,
  t2.trip_id AS trip_id_2,
  t1.origin_location_id,
  t1.destination_location_id,
  DATE(t1.scheduled_departure) AS departure_date,
  t1.actual_departure AS actual_departure_1,
  t2.actual_departure AS actual_departure_2
FROM transportation.trips AS t1
JOIN transportation.trips AS t2
  ON t1.origin_location_id = t2.origin_location_id
  AND t1.destination_location_id = t2.destination_location_id
  AND DATE(t1.scheduled_departure) = DATE(t2.scheduled_departure)
  AND t1.trip_id < t2.trip_id
WHERE
  t1.actual_departure IS NOT NULL
  AND t2.actual_departure IS NOT NULL
  AND ABS(EXTRACT(EPOCH FROM (t1.actual_departure - t2.actual_departure))) <= 7200;


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.diagnoses ( diagnosis_id.text, record_id.text, patient_id.text, doctor_id.text, diagnosis_code.text, code_type.text, description.text, diagnosis_date.date, status.text, is_chronic.boolean )
CREATE TABLE healthcare.prescriptions ( prescription_id.text, record_id.text, patient_id.text, doctor_id.text, medication_id.text, dosage.text, frequency.text, route.text, start_date.date, end_date.date, quantity_dispensed.numeric, refills_allowed.integer, prescription_date.timestamp )
CREATE TABLE healthcare.patient_insurance ( patient_insurance_id.text, patient_id.text, plan_id.text, policy_number.text, group_number.text, subscriber_name.text, effective_date.date, expiration_date.date, is_primary.boolean )

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

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


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE insurance.customers ( customer_id.text, first_name.text, last_name.text, date_of_birth.date, ssn_hash.text, address_line1.text, address_line2.text, city.text, state.text, zip_code.text, country.text, phone_number.text, email.text, created_at.timestamp, updated_at.timestamp, status.text )
CREATE TABLE insurance.policies (
    policy_id character varying(64) NOT NULL, -- unique identifier for the policy
    customer_id character varying(64) NOT NULL, -- identifier for the policyholder (FK to customers)
    product_id character varying(64) NOT NULL, -- identifier for the insurance product (FK to insurance_products)
    agent_id character varying(64), -- identifier for the agent who sold the policy (FK to agents)
    policy_number character varying(100) NOT NULL UNIQUE, -- customer-facing policy number
    start_date date NOT NULL, -- date the policy coverage begins
    end_date date NOT NULL, -- date the policy coverage ends
    premium_amount numeric(12, 2) NOT NULL, -- total premium for the policy term
    coverage_limit numeric(15, 2) NOT NULL, -- maximum amount covered
    deductible numeric(10, 2) NOT NULL, -- amount customer pays before coverage kicks in
    status character varying(30) NOT NULL, -- e.g., Active, Expired, Cancelled, Pending
    issued_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, -- when the policy was issued
    cancellation_date date,
    cancellation_reason text,
    PRIMARY KEY (policy_id)
)
CREATE TABLE insurance.claims ( claim_id character varying(64) NOT NULL, policy_id character varying(64) NOT NULL, customer_id character varying(64) NOT NULL, incident_date timestamp NOT NULL, reported_date timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, description text NOT NULL, estimated_loss numeric(15, 2), status character varying(30) NOT NULL, settlement_amount numeric(15, 2), settlement_date date, claim_handler_id character varying(64), police_report_number character varying(100), PRIMARY KEY (claim_id) )
CREATE TABLE insurance.insurance_products ( product_id.text, product_name.text, product_type.text, description.text, base_premium.numeric, coverage_details.text, underwriting_rules.text, is_active.boolean, created_at.timestamp, updated_at.timestamp )
CREATE TABLE insurance.agents ( agent_id.text, first_name.text, last_name.text, agency_name.text, license_number.text, license_state.text, contact_email.text, contact_phone.text, hire_date.date, termination_date.date, status.text, commission_rate.numeric, manager_id.text )
CREATE TABLE insurance.premium_payments ( payment_id text, policy_id text, customer_id text, payment_date timestamp, amount_paid numeric, payment_method text, transaction_reference text, due_date date, payment_period_start date, payment_period_end date, status text )
CREATE TABLE insurance.policy_beneficiaries ( beneficiary_id text, policy_id text, customer_id text, first_name text, last_name text, relationship text, percentage_share numeric, contact_info text, added_at timestamp )

[User] I want to retrieve all agents along with the number of active policies they've sold and the average premium amount of those active policies. Please include agent_id, first_name, last_name, policy_count, avg_premium. Sort the results by policy_count in descending order.

[Assistant]
SELECT a.agent_id, a.first_name, a.last_name, COUNT(p.policy_id) AS policy_count, AVG(p.premium_amount) AS avg_premium
FROM insurance.agents a
LEFT JOIN insurance.policies p
  ON a.agent_id = p.agent_id AND p.status = 'Active'
GROUP BY a.agent_id, a.first_name, a.last_name
ORDER BY policy_count DESC;

[User] Actually, only consider policies where the coverage_limit is above 500000, and include only agents with more than 5 such policies.

[Assistant]
SELECT a.agent_id, a.first_name, a.last_name, COUNT(p.policy_id) AS policy_count, AVG(p.premium_amount) AS avg_premium
FROM insurance.agents a
JOIN insurance.policies p
  ON a.agent_id = p.agent_id
WHERE p.status = 'Active'
  AND p.coverage_limit > 500000
GROUP BY a.agent_id, a.first_name, a.last_name
HAVING COUNT(p.policy_id) > 5
ORDER BY policy_count DESC;

[User] Add the agent's agency_name and contact_email to the results.

[Assistant]
SELECT a.agent_id, a.first_name, a.last_name, a.agency_name, a.contact_email,
       COUNT(p.policy_id) AS policy_count, AVG(p.premium_amount) AS avg_premium
FROM insurance.agents a
JOIN insurance.policies p
  ON a.agent_id = p.agent_id
WHERE p.status = 'Active'
  AND p.coverage_limit > 500000
GROUP BY a.agent_id, a.first_name, a.last_name, a.agency_name, a.contact_email
HAVING COUNT(p.policy_id) > 5
ORDER BY policy_count DESC;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE healthcare.patients ( patient_id.text, first_name.text, last_name.text, date_of_birth.date, gender.text, address.text, phone_number.text, email.text, emergency_contact_name.text, emergency_contact_phone.text, created_at.timestamp, updated_at.timestamp )
CREATE TABLE healthcare.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.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.medications ( medication_id text, medication_name text, generic_name text, manufacturer text, ndc_code text, description text )
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 character varying(64) NOT NULL, -- unique identifier for this patient-plan link
    patient_id character varying(64) NOT NULL, -- FK to patients table
    plan_id character varying(64) NOT NULL, -- FK to insurance_plans table
    policy_number character varying(100) NOT NULL, -- patient's policy number
    group_number character varying(100), -- group number, if applicable
    subscriber_name character varying(200), -- name of the primary policy holder
    effective_date date NOT NULL, -- date the coverage begins
    expiration_date date, -- date the coverage ends (if known)
    is_primary boolean NOT NULL DEFAULT true, -- indicates if this is the primary insurance
    PRIMARY KEY (patient_insurance_id),
    UNIQUE (patient_id, plan_id, policy_number) -- ensure a patient doesn't have the same policy twice
)

[User] List all patients who have had appointments and were prescribed a medication manufactured by 'Merck'. Show the patient ID, full name, appointment ID, and medication name.

[Assistant]
SELECT DISTINCT p.patient_id, p.first_name, p.last_name, a.appointment_id, m.medication_name
FROM healthcare.patients p
JOIN healthcare.appointments a ON p.patient_id = a.patient_id
JOIN healthcare.medical_records mr ON a.appointment_id = mr.appointment_id
JOIN healthcare.prescriptions pr ON mr.record_id = pr.record_id
JOIN healthcare.medications m ON pr.medication_id = m.medication_id
WHERE m.manufacturer = 'Merck';

[User] Only include patients who had more than one appointment where they were prescribed a Merck medication, and show the count of such appointments.

[Assistant]
SELECT p.patient_id, p.first_name, p.last_name, COUNT(DISTINCT a.appointment_id) AS appointment_count
FROM healthcare.patients p
JOIN healthcare.appointments a ON p.patient_id = a.patient_id
JOIN healthcare.medical_records mr ON a.appointment_id = mr.appointment_id
JOIN healthcare.prescriptions pr ON mr.record_id = pr.record_id
JOIN healthcare.medications m ON pr.medication_id = m.medication_id
WHERE m.manufacturer = 'Merck'
GROUP BY p.patient_id, p.first_name, p.last_name
HAVING COUNT(DISTINCT a.appointment_id) > 1;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE hospitality_technology.properties ( property_id.text, property_name.text, address_line1.text, address_line2.text, city.text, state_province.text, postal_code.text, country_code.text, phone_number.text, email_address.text, property_type.text, star_rating.numeric, timezone.text, manager_staff_id.text, created_at.timestamp, updated_at.timestamp )
CREATE TABLE hospitality_technology.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.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.service_orders ( order_id.text, reservation_id.text, guest_id.text, service_id.text, staff_id_ordered.text, staff_id_delivered.text, order_timestamp.timestamp, delivery_timestamp.timestamp, quantity.integer, unit_price.numeric, total_price.numeric, status.text, notes.text, bill_id.text )
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 )

[User] Show me all properties in California with a star rating above 4.0, along with their room types and base rates, ordered by star rating in descending order.

[Assistant] SELECT p.property_name, p.star_rating, rt.type_name, rt.base_rate FROM hospitality_technology.properties p JOIN hospitality_technology.room_types rt ON p.property_id = rt.property_id WHERE p.state_province = 'California' AND p.star_rating > 4.0 ORDER BY p.star_rating DESC;

[User] Now, filter the results to only include room types with a max occupancy of at least 4 people and a base rate below $300.

[Assistant] SELECT p.property_name, p.star_rating, rt.type_name, rt.base_rate, rt.max_occupancy FROM hospitality_technology.properties p JOIN hospitality_technology.room_types rt ON p.property_id = rt.property_id WHERE p.state_province = 'California' AND p.star_rating > 4.0 AND rt.max_occupancy >= 4 AND rt.base_rate < 300 ORDER BY p.star_rating 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 transportation.drivers ( driver_id.text, employee_id.text, first_name.text, last_name.text, license_number.text, license_expiry_date.date, contact_number.text, email.text, hire_date.date, status.text )
CREATE TABLE transportation.routes ( route_id.text, route_number.text, description.text, origin_location_id.text, destination_location_id.text, distance_km.numeric, estimated_duration_minutes.integer, type.text )
CREATE TABLE transportation.trips ( trip_id.text, route_id.text, vehicle_id.text, driver_id.text, scheduled_departure.timestamp, actual_departure.timestamp, scheduled_arrival.timestamp, actual_arrival.timestamp, origin_location_id.text, destination_location_id.text, status.text, passenger_count.integer, cargo_manifest_id.text )
CREATE TABLE transportation.locations ( location_id.text, name.text, type.text, address_line1.text, city.text, state_province.text, postal_code.text, country.text, latitude.numeric, longitude.numeric, timezone.text )
CREATE TABLE transportation.maintenance_logs ( log_id.text, vehicle_id.text, service_date.date, odometer_reading.integer, service_type.text, description.text, cost.numeric, mechanic_name.text, next_service_due_date.date )
CREATE TABLE transportation.fuel_logs ( fuel_log_id.text, vehicle_id.text, trip_id.text, log_timestamp.timestamp, fuel_type.text, quantity.numeric, unit.text, cost_per_unit.numeric, total_cost.numeric, odometer_reading.integer, location_id.text )
CREATE TABLE transportation.passengers ( passenger_id.text, first_name.text, last_name.text, email.text, phone_number.text, date_of_birth.date, loyalty_program_id.text, created_at.timestamp )
CREATE TABLE transportation.bookings ( booking_id.text, passenger_id.text, trip_id.text, seat_number.text, booking_time.timestamp, status.text, fare.numeric, payment_transaction_id.text, special_requests.text )

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

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


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 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.insurance_products ( product_id character varying(64) NOT NULL, product_name character varying(150) NOT NULL, product_type character varying(50) NOT NULL, description text, base_premium numeric(10, 2) NOT NULL, coverage_details text, underwriting_rules text, is_active boolean NOT NULL DEFAULT true, created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, updated_at timestamp, PRIMARY KEY (product_id) )
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, claim_id.text, document_type.text, file_name.text, file_path.text, file_size_bytes.integer, mime_type.text, uploaded_by.text, uploaded_at.timestamp, description.text )
CREATE TABLE insurance.policy_beneficiaries ( beneficiary_id.text, policy_id.text, customer_id.text, first_name.text, last_name.text, relationship.text, percentage_share.numeric, contact_info.text, added_at.timestamp )

[User] Show the first name and last name of customers along with the payment method for all their premium payments.

[Assistant] SELECT T1.first_name, T1.last_name, T2.payment_method FROM insurance.customers AS T1 JOIN insurance.premium_payments AS T2 ON T1.customer_id = T2.customer_id

[User] Only include payments made using 'credit card'.

[Assistant] SELECT T1.first_name, T1.last_name, T2.payment_method FROM insurance.customers AS T1 JOIN insurance.premium_payments AS T2 ON T1.customer_id = T2.customer_id WHERE T2.payment_method = 'credit card'

[User] And restrict the results to payments made in the year 2024.

[Assistant] SELECT T1.first_name, T1.last_name, T2.payment_method FROM insurance.customers AS T1 JOIN insurance.premium_payments AS T2 ON T1.customer_id = T2.customer_id WHERE T2.payment_method = 'credit card' AND T2.payment_date >= '2024-01-01' AND T2.payment_date < '2025-01-01'


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE 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.assets ( asset_id text, name text, symbol text, type text )
CREATE TABLE trading_platform.dapps ( dapp_id text, name text, description text, url text )
CREATE TABLE trading_platform.peers ( peer_id.text, ip_address.text, port.integer, last_seen.timestamp )
CREATE TABLE trading_platform.metadata ( metadata_id character varying(64) NOT NULL, asset_id character varying(64) NOT NULL, key character varying(128) NOT NULL, value text NOT NULL, PRIMARY KEY (metadata_id) )
CREATE TABLE trading_platform.logs ( log_id text PRIMARY KEY, user_id text, action text, details text, logged_at timestamp )
CREATE TABLE trading_platform.notifications ( notification_id text, user_id text, message text, sent_at timestamp, read_at timestamp )

[User] For each user, show their username and the number of unique IP addresses from the peers table where the port is less than 2000.

[Assistant]
SELECT u.username, COUNT(DISTINCT p.ip_address) AS unique_ip_count
FROM trading_platform.users u
JOIN trading_platform.peers p ON u.user_id = p.peer_id
WHERE p.port < 2000
GROUP BY u.username;

[User] This query isn't working because peer_id and user_id don't always match. Could you just show the total number of unique IPs with port < 2000 in the peers table, excluding user data?

[Assistant]
SELECT COUNT(DISTINCT ip_address) AS unique_ip_count
FROM trading_platform.peers
WHERE port < 2000;

[User] Now, for each port number below 2000, show the count of unique IP addresses using that port.

[Assistant]
SELECT port, COUNT(DISTINCT ip_address) AS unique_ip_count
FROM trading_platform.peers
WHERE port < 2000
GROUP BY port;

[User] Actually, only show ports where more than one unique IP address exists.

[Assistant]
SELECT port, COUNT(DISTINCT ip_address) AS unique_ip_count
FROM trading_platform.peers
WHERE port < 2000
GROUP BY port
HAVING COUNT(DISTINCT ip_address) > 1;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE web3.users (
    user_id character varying(64) NOT NULL,  -- unique identifier for the user
    username character varying(128) NOT NULL, -- username of the user
    email character varying(128) NOT NULL, -- email address of the user
    password_hash text NOT NULL, -- hashed password of the user
    created_at timestamp NOT NULL, -- time when the user account was created
    PRIMARY KEY (user_id)
)

[User] Count the number of users for each email domain.

[Assistant]
SELECT split_part(email, '@', 2) AS domain, COUNT(*) AS user_count
FROM web3.users
GROUP BY domain;

[User] Filter to domains with more than 5 users.

[Assistant]
SELECT split_part(email, '@', 2) AS domain, COUNT(*) AS user_count
FROM web3.users
GROUP BY domain
HAVING COUNT(*) > 5;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE legal_services.clients ( client_id character varying(64) NOT NULL, first_name character varying(100) NOT NULL, last_name character varying(100) NOT NULL, company_name character varying(200), email character varying(128) UNIQUE NOT NULL, phone character varying(32), address text, date_registered timestamp NOT NULL, status character varying(32) NOT NULL, PRIMARY KEY (client_id) )
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.law_firms ( firm_id character varying(64) NOT NULL, firm_name character varying(200) NOT NULL, address text NOT NULL, phone character varying(32), website character varying(255), founded_date date, managing_partner_id character varying(64), PRIMARY KEY (firm_id) )
CREATE TABLE legal_services.cases ( case_id character varying(64) NOT NULL, case_number character varying(100) UNIQUE, case_name text NOT NULL, client_id character varying(64) NOT NULL, lead_lawyer_id character varying(64) NOT NULL, case_type character varying(100) NOT NULL, status character varying(50) NOT NULL, date_opened timestamp NOT NULL, date_closed timestamp, description text, court_jurisdiction character varying(128), PRIMARY KEY (case_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.time_entries ( entry_id character varying(64) NOT NULL, case_id character varying(64) NOT NULL, lawyer_id character varying(64) NOT NULL, date_worked date NOT NULL, hours_spent numeric(5, 2) NOT NULL CHECK (hours_spent > 0), billing_rate numeric(10, 2) NOT NULL, description text NOT NULL, is_billable boolean DEFAULT true, is_billed boolean DEFAULT false, invoice_id character varying(64), created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, PRIMARY KEY (entry_id) )
CREATE TABLE legal_services.appointments ( appointment_id character varying(64) NOT NULL, client_id character varying(64) NOT NULL, lawyer_id character varying(64) NOT NULL, case_id character varying(64), start_time timestamp NOT NULL, end_time timestamp NOT NULL, location text, subject character varying(255), notes text, status character varying(50) NOT NULL, created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, PRIMARY KEY (appointment_id) )

[User] List all clients along with their case_number and case_type for cases that are currently 'Open'.

[Assistant]
SELECT c.first_name, c.last_name, c.email, cs.case_number, cs.case_type
FROM legal_services.clients AS c
JOIN legal_services.cases AS cs
  ON c.client_id = cs.client_id
WHERE cs.status = 'Open';


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.customers ( customer_id.text, first_name.text, last_name.text, date_of_birth.date, ssn_hash.text, address.text, city.text, state.text, zip_code.text, country.text, email.text, phone_number.text, created_at.timestamp, status.text, risk_profile.text )

[User] Which cities have more than 50 customers, and what is the average customer age in each?

[Assistant]
SELECT city, COUNT(*) AS customer_count, AVG(EXTRACT(YEAR FROM AGE(CURRENT_DATE, date_of_birth))) AS avg_age
FROM financial_services.customers
GROUP BY city
HAVING COUNT(*) > 50;

[User] Can you also show the minimum and maximum date_of_birth for customers in each city?

[Assistant]
SELECT city, COUNT(*) AS customer_count, AVG(EXTRACT(YEAR FROM AGE(CURRENT_DATE, date_of_birth))) AS avg_age, MIN(date_of_birth) AS earliest_birth, MAX(date_of_birth) AS latest_birth
FROM financial_services.customers
GROUP BY city
HAVING COUNT(*) > 50;

[User] Now, only include cities located in the state of Texas.

[Assistant]
SELECT city, COUNT(*) AS customer_count, AVG(EXTRACT(YEAR FROM AGE(CURRENT_DATE, date_of_birth))) AS avg_age, MIN(date_of_birth) AS earliest_birth, MAX(date_of_birth) AS latest_birth
FROM financial_services.customers
WHERE state = 'TX'
GROUP BY city
HAVING COUNT(*) > 50;

[User] And sort the output by customer_count descending.

[Assistant]
SELECT city, COUNT(*) AS customer_count, AVG(EXTRACT(YEAR FROM AGE(CURRENT_DATE, date_of_birth))) AS avg_age, MIN(date_of_birth) AS earliest_birth, MAX(date_of_birth) AS latest_birth
FROM financial_services.customers
WHERE state = 'TX'
GROUP BY city
HAVING COUNT(*) > 50
ORDER BY customer_count DESC;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE healthcare.patients ( patient_id character varying(64) NOT NULL, first_name character varying(100) NOT NULL, last_name character varying(100) NOT NULL, date_of_birth date NOT NULL, gender character varying(10), address text, phone_number character varying(20), email character varying(128) UNIQUE, emergency_contact_name character varying(200), emergency_contact_phone character varying(20), created_at timestamp with time zone NOT NULL DEFAULT current_timestamp, updated_at timestamp with time zone NOT NULL DEFAULT current_timestamp, PRIMARY KEY (patient_id) )
CREATE TABLE healthcare.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.medical_records ( record_id text PRIMARY KEY, patient_id text, appointment_id text, doctor_id text, record_date timestamp, chief_complaint text, present_illness_history text, past_medical_history text, physical_examination_notes text, assessment text, treatment_plan text, vitals text, created_at timestamp )
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.medications ( medication_id text PRIMARY KEY, medication_name text, generic_name text, manufacturer text, ndc_code text, description text )
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 )

[User] List patient_id, first_name, last_name, and date_of_birth for all patients older than 65 years.

[Assistant]
SELECT patient_id, first_name, last_name, date_of_birth
FROM healthcare.patients
WHERE date_of_birth < CURRENT_DATE - INTERVAL '65 years';


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.lawyers ( lawyer_id.text, first_name.text, last_name.text, bar_number.text, firm_id.text, email.text, phone.text, specialization.text, hire_date.timestamp, is_partner.boolean )
CREATE TABLE legal_services.law_firms ( firm_id.text, firm_name.text, address.text, phone.text, website.text, founded_date.date, managing_partner_id.text )
CREATE TABLE legal_services.cases ( case_id.text, case_number.text, case_name.text, client_id.text, lead_lawyer_id.text, case_type.text, status.text, date_opened.timestamp, date_closed.timestamp, description.text, court_jurisdiction.text )
CREATE TABLE legal_services.time_entries ( entry_id.text, case_id.text, lawyer_id.text, date_worked.date, hours_spent.numeric, billing_rate.numeric, description.text, is_billable.boolean, is_billed.boolean, invoice_id.text, created_at.timestamp )

[User] List the full name (first and last) and specialization of all lawyers who work for law firms founded before the year 2000.

[Assistant] SELECT T1.first_name, T1.last_name, T1.specialization FROM lawyers AS T1 JOIN law_firms AS T2 ON T1.firm_id = T2.firm_id WHERE T2.founded_date < '2000-01-01'

[User] From that list, could you only show those lawyers whose specialization is 'Environmental Law'?

[Assistant] SELECT T1.first_name, T1.last_name, T1.specialization FROM lawyers AS T1 JOIN law_firms AS T2 ON T1.firm_id = T2.firm_id WHERE T2.founded_date < '2000-01-01' AND T1.specialization = 'Environmental Law'

[User] Also include their hire date and order the results by specialization then hire date.

[Assistant] SELECT T1.first_name, T1.last_name, T1.specialization, T1.hire_date FROM lawyers AS T1 JOIN law_firms AS T2 ON T1.firm_id = T2.firm_id WHERE T2.founded_date < '2000-01-01' AND T1.specialization = 'Environmental Law' ORDER BY T1.specialization, T1.hire_date


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 erc20_balances ( block_number.bigint, contract_address.text, wallet_address.text, amount.text, pk.text )
CREATE TABLE nft_holders (
    block_number bigint NOT NULL, -- Block number containing the transaction
    contract_address varchar NOT NULL, -- Event contract address
    wallet_address varchar NOT NULL, -- The wallet address for the contract(with bloom filter)
    token_id varchar NOT NULL, -- NFT token id
    contract_type varchar NOT NULL, -- NFT contract type
    amount varchar NOT NULL, -- Number of held NFTs
    pk varchar NOT NULL  -- The last string partition of the contract.
)
CREATE TABLE sui_nfts ( object_id varchar, status varchar, collection_type varchar, package_id varchar, previous_transaction varchar, display varchar, owner varchar, name varchar )
CREATE TABLE token_prices ( uuid varchar, blockchain varchar, address varchar, decimals bigint, symbol varchar, price real, timestamp timestamp )
CREATE TABLE token_prices_latest (
    blockchain varchar(36) NOT NULL, -- blockchain fields for the functionType  in contract
    address varchar(42) NOT NULL, -- address fields for the functionType  in contract
    decimals bigint NOT NULL, -- decimals fields for the functionType  in contract
    symbol varchar(36) NOT NULL, -- symbol fields for the functionType  in contract
    price real NOT NULL, -- price fields for the functionType  in contract
    timestamp timestamp(6) NOT NULL  -- timestamp fields for the functionType  in contract
)
CREATE TABLE erc20_approval ( block_number bigint, block_timestamp timestamp, transaction_index integer, transaction_hash text, log_index integer, contract_address text, pk integer )
CREATE TABLE token_balances ( block_number bigint, block_timestamp timestamp, tick text, wallet_address text, total_supply decimal, amount decimal )
CREATE TABLE token_info (
    block_timestamp timestamp(3) NOT NULL, -- Timestamp of the block containing the inscription (matches block_timestamp in transactions table)
    block_number bigint NOT NULL, -- Block number containing the inscription (matches block_number in transactions table)
    tx_index integer NOT NULL, -- Index of the transaction containing the inscription (matches transaction_index in transactions table)
    tx_hash varchar(66) NOT NULL, -- Unique identifier of the transaction containing the inscription (matches hash in transactions table)
    tick varchar NOT NULL, -- Token tick
    max_supply decimal(38,0) NOT NULL, -- Max supply
    lim decimal(38,0) NOT NULL, -- Limit of each mint
    wlim decimal(38,0) NOT NULL, -- Limit of each address can maximum mint
    dec integer NOT NULL, -- Decimal for minimum divie
    creator varchar(42) NOT NULL  -- Address originating the inscription (matches from_address in transactions table)
)
CREATE TABLE token_info_bitcoin ( block_timestamp timestamp(3) NOT NULL, block_number bigint NOT NULL, tx_index integer NOT NULL, tx_hash varchar(66) NOT NULL, tick varchar(255) NOT NULL, max_supply decimal(38,0) NOT NULL, lim decimal(38,0) NOT NULL, wlim decimal(38,0) NOT NULL, dec integer NOT NULL, creator varchar(42) NOT NULL )
CREATE TABLE token_activities_avalanche ( block_timestamp timestamp(3) NOT NULL, block_number bigint NOT NULL, tx_index integer NOT NULL, tx_hash varchar(66) NOT NULL, log_index integer NOT NULL, type varchar(20) NOT NULL, tick varchar(255) NOT NULL, id varchar(255) NOT NULL, amt decimal(38,0) NOT NULL, from_address varchar(42) NOT NULL, to_address varchar(42) NOT NULL )
CREATE TABLE token_balances_avalanche ( block_number bigint, block_timestamp timestamp, tick text, wallet_address text, total_supply decimal, amount decimal )

[User] Find all wallets that hold at least one NFT and also hold ERC-20 tokens.

[Assistant]
SELECT DISTINCT nh.wallet_address
FROM nft_holders nh
JOIN erc20_balances eb
  ON nh.wallet_address = eb.wallet_address;

[User] Now show the count of distinct NFTs and count of distinct ERC-20 token contracts held by each such wallet.

[Assistant]
SELECT nh.wallet_address,
       COUNT(DISTINCT nh.contract_address || '-' || nh.token_id) AS nft_count,
       COUNT(DISTINCT eb.contract_address) AS erc20_count
FROM nft_holders nh
JOIN erc20_balances eb
  ON nh.wallet_address = eb.wallet_address
GROUP BY nh.wallet_address;

[User] Finally, only include wallets where erc20_count > 1 and nft_count > 2, and order by erc20_count descending.

[Assistant]
SELECT nh.wallet_address,
       COUNT(DISTINCT nh.contract_address || '-' || nh.token_id) AS nft_count,
       COUNT(DISTINCT eb.contract_address) AS erc20_count
FROM nft_holders nh
JOIN erc20_balances eb
  ON nh.wallet_address = eb.wallet_address
GROUP BY nh.wallet_address
HAVING COUNT(DISTINCT eb.contract_address) > 1
   AND COUNT(DISTINCT nh.contract_address || '-' || nh.token_id) > 2
ORDER BY erc20_count DESC;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE legal_services.law_firms ( firm_id text, firm_name text, address text, phone text, website text, founded_date date, managing_partner_id text )
CREATE TABLE legal_services.cases ( case_id character varying(64) NOT NULL, case_number character varying(100) UNIQUE, case_name text NOT NULL, client_id character varying(64) NOT NULL, lead_lawyer_id character varying(64) NOT NULL, case_type character varying(100) NOT NULL, status character varying(50) NOT NULL, date_opened timestamp NOT NULL, date_closed timestamp, description text, court_jurisdiction character varying(128), PRIMARY KEY (case_id) )
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 )

[User] List the case number and name for all cases that do not have any linked invoices.

[Assistant] SELECT T1.case_number, T1.case_name FROM cases AS T1 LEFT JOIN invoices AS T2 ON T1.case_id = T2.case_id WHERE T2.invoice_id IS NULL;

[User] Also include the date the case was opened, and restrict the list to cases opened after 2023-01-01.

[Assistant] SELECT T1.case_number, T1.case_name, T1.date_opened FROM cases AS T1 LEFT JOIN invoices AS T2 ON T1.case_id = T2.case_id WHERE T2.invoice_id IS NULL AND T1.date_opened > '2023-01-01';


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE 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 )

[User] List each patient and the total number of chronic diagnoses they have received, as well as the number of distinct doctors who have made those diagnoses.

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

[User] Only include patients who have received diagnoses recorded as 'Active' status.

[Assistant] SELECT patient_id, COUNT(*) AS chronic_diagnoses_count, COUNT(DISTINCT doctor_id) AS distinct_doctors FROM healthcare.diagnoses WHERE is_chronic = TRUE AND status = 'Active' GROUP BY patient_id;