[User] Calculate the total PNL and total Net Flow for all tokens recorded on the 'Arbitrum' chain.

[Assistant] SELECT SUM(pnl) as total_pnl, SUM(net_flow) as total_net_flow FROM smart_money_token_performance WHERE chain = 'Arbitrum';

[User] Can you calculate the total PNL and total Net Flow for *all* chains? Show the chain, total PNL, and total Net Flow, ordered by total PNL in descending order.

[Assistant] SELECT chain, SUM(pnl) as total_pnl, SUM(net_flow) as total_net_flow FROM smart_money_token_performance GROUP BY chain ORDER BY total_pnl DESC;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE smart_money_token_performance ( token_address character varying(100) NOT NULL, token_symbol character varying(100), pnl numeric(38,2), net_flow numeric(38,2), avg_cost numeric(38,16), price double precision, realized_ratio numeric(10,2), roi numeric(10,2), chain character varying(100) )


[User] List all patients who have insurance plans with group numbers, showing their patient IDs and the count of such plans per patient.

[Assistant] SELECT patient_id, COUNT(*) AS plan_count FROM healthcare.patient_insurance WHERE group_number IS NOT NULL GROUP BY patient_id;

[User] Actually, I only need patients who have more than 2 such plans.

[Assistant] SELECT patient_id, COUNT(*) AS plan_count FROM healthcare.patient_insurance WHERE group_number IS NOT NULL GROUP BY patient_id HAVING COUNT(*) > 2;

[User] Can you also include the earliest effective date among these plans for each patient?

[Assistant] SELECT patient_id, COUNT(*) AS plan_count, MIN(effective_date) AS earliest_effective_date FROM healthcare.patient_insurance WHERE group_number IS NOT NULL GROUP BY patient_id HAVING COUNT(*) > 2;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
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] For each sector, could you show the sum of volume and the average close price from market_data, including the sector name?

[Assistant]
SELECT s.sector, SUM(md.volume) AS total_volume, AVG(md.close_price) AS avg_close_price
FROM financial_services.securities s
JOIN financial_services.market_data md ON s.security_id = md.security_id
GROUP BY s.sector;

[User] Could you also include the maximum high price for each sector in the result?

[Assistant]
SELECT s.sector, SUM(md.volume) AS total_volume, AVG(md.close_price) AS avg_close_price, MAX(md.high_price) AS max_high_price
FROM financial_services.securities s
JOIN financial_services.market_data md ON s.security_id = md.security_id
GROUP BY s.sector;

[User] Now, only include sectors where the total_volume is at least 1000000, and sort by max_high_price descending.

[Assistant]
SELECT s.sector, SUM(md.volume) AS total_volume, AVG(md.close_price) AS avg_close_price, MAX(md.high_price) AS max_high_price
FROM financial_services.securities s
JOIN financial_services.market_data md ON s.security_id = md.security_id
GROUP BY s.sector
HAVING SUM(md.volume) >= 1000000
ORDER BY max_high_price DESC;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE financial_services.securities ( security_id.text, ticker_symbol.text, isin_code.text, cusip_code.text, security_name.text, security_type.text, exchange.text, currency.text, issuer_name.text, sector.text, last_updated.timestamp )
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) )


[User] I want to list all insurance plans along with the number of medical records that have a record_date in 2024. Display plan_id, plan_name, and the total medical records.

[Assistant]
SELECT ip.plan_id, ip.plan_name, COUNT(mr.record_id) AS total_medical_records
FROM healthcare.insurance_plans ip
LEFT JOIN healthcare.medical_records mr ON 1=0 -- there is no direct relationship in schema, so no records will be counted
WHERE mr.record_date >= '2024-01-01' AND mr.record_date < '2025-01-01'
GROUP BY ip.plan_id, ip.plan_name;

[User] Since there's no direct relationship, can you adjust it to just show all insurance plans of type 'EPO' with their plan_id and plan_name?

[Assistant]
SELECT plan_id, plan_name
FROM healthcare.insurance_plans
WHERE plan_type = 'EPO';

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE healthcare.medical_records (
    record_id character varying(64) NOT NULL,  -- unique identifier for the medical record entry
    patient_id character varying(64) NOT NULL, -- FK to patients table
    appointment_id character varying(64) UNIQUE, -- FK to appointments table (can be null if record not tied to specific appt)
    doctor_id character varying(64) NOT NULL, -- FK to doctors table (doctor creating the record)
    record_date timestamp with time zone NOT NULL, -- date the record/observation was made
    chief_complaint text, -- patient's primary reason for visit
    present_illness_history text, -- detailed history of the current issue
    past_medical_history text, -- relevant past conditions/surgeries
    physical_examination_notes text, -- findings from the physical exam
    assessment text, -- doctor's assessment/diagnosis summary
    treatment_plan text, -- planned course of action
    vitals jsonb, -- store vitals like BP, HR, Temp as structured JSON
    created_at timestamp with time zone NOT NULL DEFAULT current_timestamp,
    PRIMARY KEY (record_id)
)
CREATE TABLE healthcare.insurance_plans ( plan_id text, plan_name text, insurance_provider text, plan_type text, contact_phone text, website text )


[User] Which exchanges hold the largest total USD value of tokens on the BSC chain in the most recent snapshot, and what is the top token (by usd_value) held by each exchange?

[Assistant]
WITH latest_snapshot AS (
  SELECT MAX(snapshot_time) AS max_time FROM cex_token_balance
),
exchange_totals AS (
  SELECT
    c.exchange,
    SUM(c.usd_value) AS total_usd_value
  FROM cex_token_balance c
  JOIN latest_snapshot l ON c.snapshot_time = l.max_time
  WHERE c.chain = 'BSC'
  GROUP BY c.exchange
),
top_token_per_exchange AS (
  SELECT c.exchange, c.token_symbol, c.usd_value, ROW_NUMBER() OVER (PARTITION BY c.exchange ORDER BY c.usd_value DESC) AS rn
  FROM cex_token_balance c
  JOIN latest_snapshot l ON c.snapshot_time = l.max_time
  WHERE c.chain = 'BSC'
)
SELECT
  t.exchange,
  e.total_usd_value,
  t.token_symbol AS top_token_symbol,
  t.usd_value AS top_token_usd_value
FROM exchange_totals e
JOIN top_token_per_exchange t ON e.exchange = t.exchange AND t.rn = 1
ORDER BY e.total_usd_value DESC;

[User] Can you add the number of distinct tokens each exchange holds on BSC in the latest snapshot to the result?

[Assistant]
WITH latest_snapshot AS (
  SELECT MAX(snapshot_time) AS max_time FROM cex_token_balance
),
exchange_totals AS (
  SELECT
    c.exchange,
    SUM(c.usd_value) AS total_usd_value,
    COUNT(DISTINCT c.token_symbol) AS token_count
  FROM cex_token_balance c
  JOIN latest_snapshot l ON c.snapshot_time = l.max_time
  WHERE c.chain = 'BSC'
  GROUP BY c.exchange
),
top_token_per_exchange AS (
  SELECT c.exchange, c.token_symbol, c.usd_value, ROW_NUMBER() OVER (PARTITION BY c.exchange ORDER BY c.usd_value DESC) AS rn
  FROM cex_token_balance c
  JOIN latest_snapshot l ON c.snapshot_time = l.max_time
  WHERE c.chain = 'BSC'
)
SELECT
  t.exchange,
  e.total_usd_value,
  e.token_count,
  t.token_symbol AS top_token_symbol,
  t.usd_value AS top_token_usd_value
FROM exchange_totals e
JOIN top_token_per_exchange t ON e.exchange = t.exchange AND t.rn = 1
ORDER BY e.total_usd_value DESC;

[User] I'd like the results filtered so only exchanges holding more than $2,000,000 in total on BSC are included.

[Assistant]
WITH latest_snapshot AS (
  SELECT MAX(snapshot_time) AS max_time FROM cex_token_balance
),
exchange_totals AS (
  SELECT
    c.exchange,
    SUM(c.usd_value) AS total_usd_value,
    COUNT(DISTINCT c.token_symbol) AS token_count
  FROM cex_token_balance c
  JOIN latest_snapshot l ON c.snapshot_time = l.max_time
  WHERE c.chain = 'BSC'
  GROUP BY c.exchange
  HAVING SUM(c.usd_value) > 2000000
),
top_token_per_exchange AS (
  SELECT c.exchange, c.token_symbol, c.usd_value, ROW_NUMBER() OVER (PARTITION BY c.exchange ORDER BY c.usd_value DESC) AS rn
  FROM cex_token_balance c
  JOIN latest_snapshot l ON c.snapshot_time = l.max_time
  WHERE c.chain = 'BSC'
)
SELECT
  t.exchange,
  e.total_usd_value,
  e.token_count,
  t.token_symbol AS top_token_symbol,
  t.usd_value AS top_token_usd_value
FROM exchange_totals e
JOIN top_token_per_exchange t ON e.exchange = t.exchange AND t.rn = 1
ORDER BY e.total_usd_value DESC;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE cex_token_balance ( snapshot_time.text, chain.text, address.text, exchange.text, token_address.text, token_symbol.text, balance.numeric, usd_value.numeric, price.numeric )


[User] For all chains, which token held by centralized exchanges (CEX) has the highest ROI according to smart money token performance? Show token symbol, chain, exchange, total USD value held on CEX, and the smart money ROI.

[Assistant]
SELECT c.token_symbol, c.chain, c.exchange, SUM(c.usd_value) AS total_usd_value, s.roi
FROM cex_token_balance c
JOIN smart_money_token_performance s ON c.token_symbol = s.token_symbol AND c.chain = s.chain
GROUP BY c.token_symbol, c.chain, c.exchange, s.roi
ORDER BY s.roi DESC
LIMIT 1;

[User] Instead of just the top one, show the top 3 tokens by ROI, and only include cases where the total USD value held on CEX is greater than $2,000,000.

[Assistant]
SELECT c.token_symbol, c.chain, c.exchange, SUM(c.usd_value) AS total_usd_value, s.roi
FROM cex_token_balance c
JOIN smart_money_token_performance s ON c.token_symbol = s.token_symbol AND c.chain = s.chain
GROUP BY c.token_symbol, c.chain, c.exchange, s.roi
HAVING SUM(c.usd_value) > 2000000
ORDER BY s.roi DESC
LIMIT 3;

[User] Add the last recorded price for each token, and sort by total_usd_value in descending order.

[Assistant]
SELECT c.token_symbol, c.chain, c.exchange, SUM(c.usd_value) AS total_usd_value, s.roi, MAX(c.price) AS last_price
FROM cex_token_balance c
JOIN smart_money_token_performance s ON c.token_symbol = s.token_symbol AND c.chain = s.chain
GROUP BY c.token_symbol, c.chain, c.exchange, s.roi
HAVING SUM(c.usd_value) > 2000000
ORDER BY total_usd_value DESC
LIMIT 3;

[User] I got duplicate tokens across exchanges. Can you show only the top exchange (with the greatest USD value) per token and chain combination?

[Assistant]
WITH cex_totals AS (
  SELECT c.token_symbol, c.chain, c.exchange, SUM(c.usd_value) AS total_usd_value, s.roi, MAX(c.price) AS last_price,
         ROW_NUMBER() OVER (PARTITION BY c.token_symbol, c.chain ORDER BY SUM(c.usd_value) DESC) as rn
  FROM cex_token_balance c
  JOIN smart_money_token_performance s ON c.token_symbol = s.token_symbol AND c.chain = s.chain
  GROUP BY c.token_symbol, c.chain, c.exchange, s.roi
  HAVING SUM(c.usd_value) > 2000000
)
SELECT token_symbol, chain, exchange, total_usd_value, roi, last_price
FROM cex_totals
WHERE rn = 1
ORDER BY total_usd_value DESC
LIMIT 3;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE project_fundraising_record ( id character varying(32) NOT NULL, project_id character varying(32) NOT NULL, project_name character varying(128) NOT NULL, rounds_name character varying(32), investment_value numeric(38,14), investment_date character varying(128), introduction character varying(128), valuation numeric(38,14) )
CREATE TABLE narrative_info ( narrative character varying(512) NOT NULL, top_3_coins text, price_change_percentage_1h double precision, price_change_percentage_24h double precision, price_change_percentage_7d double precision, market_cap double precision, volume_24h double precision, trend_rank bigint, token_num bigint )
CREATE TABLE cex_token_balance ( snapshot_time character varying(32) NOT NULL, chain character varying(128) NOT NULL, address character varying(128) NOT NULL, exchange character varying(512) NOT NULL, token_address character varying(128) NOT NULL, token_symbol character varying(512), balance numeric(38,10), usd_value numeric(38,14), price double precision )
CREATE TABLE smart_money_profit ( address character varying(100) NOT NULL, rank INT, profit numeric(38,6), roi numeric(38,2), realized_ratio numeric(38,2), most_profit_token character varying(100), last_trade_time character varying(100), chain character varying(100) )
CREATE TABLE smart_money_token_performance ( token_address character varying(100) NOT NULL, token_symbol character varying(100), pnl numeric(38,2), net_flow numeric(38,2), avg_cost numeric(38,16), price double precision, realized_ratio numeric(10,2), roi numeric(10,2), chain character varying(100) )
CREATE TABLE smart_money_token_inflow ( token_address character varying(100) NOT NULL, token_symbol character varying(100), token_amount numeric(38,2), usd_value numeric(38,2), avg_price numeric(38,6), type int, address_amount integer, narrative character varying(100), chain character varying(100) )


[User] Find medical records where the assessment mentions the generic name of any medication. Show the record ID, record date, patient ID, and the generic name mentioned.

[Assistant] SELECT T1.record_id, T1.record_date, T1.patient_id, T2.generic_name FROM healthcare.medical_records AS T1 JOIN healthcare.medications AS T2 ON T1.assessment LIKE '%' || T2.generic_name || '%' WHERE T2.generic_name IS NOT NULL AND T2.generic_name != ''

[User] Filter these results to only include records for patient 'pat123' and include the medication name in the output.

[Assistant] SELECT T1.record_id, T1.record_date, T1.patient_id, T2.generic_name, T2.medication_name FROM healthcare.medical_records AS T1 JOIN healthcare.medications AS T2 ON T1.assessment LIKE '%' || T2.generic_name || '%' WHERE T2.generic_name IS NOT NULL AND T2.generic_name != '' AND T1.patient_id = 'pat123'

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE healthcare.medical_records ( record_id text PRIMARY KEY, patient_id text, appointment_id text, doctor_id text, record_date timestamp, chief_complaint text, present_illness_history text, past_medical_history text, physical_examination_notes text, assessment text, treatment_plan text, vitals text, created_at timestamp )
CREATE TABLE healthcare.medications ( medication_id text PRIMARY KEY, medication_name text, generic_name text, manufacturer text, ndc_code text, description text )


[User] Show me all log entries for user ID 'user123'.

[Assistant] SELECT log_id, user_id, action, details, logged_at FROM trading_platform.logs WHERE user_id = 'user123' ORDER BY logged_at DESC;

[User] Show only the logs for that user where the action contains 'trade' and the log entry was created after '2024-07-01'.

[Assistant] SELECT log_id, user_id, action, details, logged_at FROM trading_platform.logs WHERE user_id = 'user123' AND action LIKE '%trade%' AND logged_at > '2024-07-01' ORDER BY logged_at DESC;

[User] Instead of listing the logs, just count how many logs for user 'user123' meet the criteria (action contains 'trade' and logged after '2024-07-01').

[Assistant] SELECT COUNT(*) FROM trading_platform.logs WHERE user_id = 'user123' AND action LIKE '%trade%' AND logged_at > '2024-07-01';

[User] Now, for that user ('user123') and timeframe (after '2024-07-01'), count how many unique action types containing 'trade' they performed.

[Assistant] SELECT COUNT(DISTINCT action) FROM trading_platform.logs WHERE user_id = 'user123' AND action LIKE '%trade%' AND logged_at > '2024-07-01';

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE trading_platform.logs ( log_id character varying(64) NOT NULL, user_id character varying(64), action character varying(128) NOT NULL, details text NOT NULL, logged_at timestamp NOT NULL, PRIMARY KEY (log_id) )


[User] List pairs of citizens who share the same email domain.

[Assistant]
SELECT c1.first_name AS first1,
       c1.last_name AS last1,
       c2.first_name AS first2,
       c2.last_name AS last2,
       SPLIT_PART(c1.contact_email, '@', 2) AS domain
FROM government_services.citizens c1
JOIN government_services.citizens c2
  ON SPLIT_PART(c1.contact_email, '@', 2) = SPLIT_PART(c2.contact_email, '@', 2)
 AND c1.citizen_id < c2.citizen_id
WHERE c1.contact_email IS NOT NULL
  AND c2.contact_email IS NOT NULL;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE government_services.citizens (
    citizen_id character varying(64) NOT NULL,  -- unique identifier for the citizen
    national_id_number character varying(128) NOT NULL UNIQUE, -- official national identification number
    first_name character varying(100) NOT NULL,
    last_name character varying(100) NOT NULL,
    date_of_birth date NOT NULL,
    gender character varying(20),
    primary_address text NOT NULL, -- full primary residential address
    contact_email character varying(128) UNIQUE,
    contact_phone character varying(32),
    registration_date timestamp NOT NULL, -- when the citizen profile was created
    is_verified boolean DEFAULT false, -- whether identity has been officially verified
    PRIMARY KEY (citizen_id)
)


[User] I want a list of all claims where at least one document is larger than 2 megabytes. Include the claim ID, incident date, and the file name of such documents.

[Assistant]
SELECT c.claim_id, c.incident_date, d.file_name
FROM insurance.claims c
JOIN insurance.claim_documents d ON c.claim_id = d.claim_id
WHERE d.file_size_bytes > 2097152;

[User] Actually, please also show the document type and only include documents uploaded after June 1, 2024.

[Assistant]
SELECT c.claim_id, c.incident_date, d.file_name, d.document_type
FROM insurance.claims c
JOIN insurance.claim_documents d ON c.claim_id = d.claim_id
WHERE d.file_size_bytes > 2097152
  AND d.uploaded_at > '2024-06-01';

[User] Add the file size in kilobytes and order the results by file size descending.

[Assistant]
SELECT c.claim_id, c.incident_date, d.file_name, d.document_type, (d.file_size_bytes/1024) AS file_size_kb
FROM insurance.claims c
JOIN insurance.claim_documents d ON c.claim_id = d.claim_id
WHERE d.file_size_bytes > 2097152
  AND d.uploaded_at > '2024-06-01'
ORDER BY d.file_size_bytes DESC;

[User] Sorry, I'm getting some records where file_size_bytes is NULL. Please exclude those from the results.

[Assistant]
SELECT c.claim_id, c.incident_date, d.file_name, d.document_type, (d.file_size_bytes/1024) AS file_size_kb
FROM insurance.claims c
JOIN insurance.claim_documents d ON c.claim_id = d.claim_id
WHERE d.file_size_bytes > 2097152
  AND d.uploaded_at > '2024-06-01'
  AND d.file_size_bytes IS NOT NULL
ORDER BY d.file_size_bytes DESC;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE insurance.claims ( claim_id text, policy_id text, customer_id text, incident_date timestamp, reported_date timestamp, description text, estimated_loss numeric, status text, settlement_amount numeric, settlement_date date, claim_handler_id text, police_report_number text )
CREATE TABLE insurance.claim_documents ( document_id text PRIMARY KEY, claim_id text, document_type text, file_name text, file_path text, file_size_bytes int, mime_type text, uploaded_by text, uploaded_at timestamp, description text )


[User] For each narrative in smart money token inflow, calculate the total usd_value and list the token symbol that has the highest liquidity from the DEX pool.

[Assistant]
SELECT i.narrative, SUM(i.usd_value) AS total_usd_inflow,
       (SELECT d.token_symbol
        FROM smart_money_token_inflow inf2
        JOIN token_dexpool_info d ON inf2.token_symbol = d.token_symbol AND inf2.chain = d.chain
        WHERE inf2.narrative = i.narrative
        ORDER BY d.liquidity DESC
        LIMIT 1) AS top_liquidity_token,
       (SELECT d.liquidity
        FROM smart_money_token_inflow inf2
        JOIN token_dexpool_info d ON inf2.token_symbol = d.token_symbol AND inf2.chain = d.chain
        WHERE inf2.narrative = i.narrative
        ORDER BY d.liquidity DESC
        LIMIT 1) AS top_liquidity
FROM smart_money_token_inflow i
GROUP BY i.narrative;

[User] Also include the average price_change_percentage_24h of that top liquidity token.

[Assistant]
SELECT i.narrative, SUM(i.usd_value) AS total_usd_inflow,
       (SELECT d.token_symbol
        FROM smart_money_token_inflow inf2
        JOIN token_dexpool_info d ON inf2.token_symbol = d.token_symbol AND inf2.chain = d.chain
        WHERE inf2.narrative = i.narrative
        ORDER BY d.liquidity DESC
        LIMIT 1) AS top_liquidity_token,
       (SELECT d.liquidity
        FROM smart_money_token_inflow inf2
        JOIN token_dexpool_info d ON inf2.token_symbol = d.token_symbol AND inf2.chain = d.chain
        WHERE inf2.narrative = i.narrative
        ORDER BY d.liquidity DESC
        LIMIT 1) AS top_liquidity,
       (SELECT d.price_change_percentage_24h
        FROM smart_money_token_inflow inf2
        JOIN token_dexpool_info d ON inf2.token_symbol = d.token_symbol AND inf2.chain = d.chain
        WHERE inf2.narrative = i.narrative
        ORDER BY d.liquidity DESC
        LIMIT 1) AS price_change_24h
FROM smart_money_token_inflow i
GROUP BY i.narrative;

[User] Filter to include only narratives that have more than 2 distinct tokens in the inflow records.

[Assistant]
SELECT i.narrative, SUM(i.usd_value) AS total_usd_inflow,
       (SELECT d.token_symbol
        FROM smart_money_token_inflow inf2
        JOIN token_dexpool_info d ON inf2.token_symbol = d.token_symbol AND inf2.chain = d.chain
        WHERE inf2.narrative = i.narrative
        ORDER BY d.liquidity DESC
        LIMIT 1) AS top_liquidity_token,
       (SELECT d.liquidity
        FROM smart_money_token_inflow inf2
        JOIN token_dexpool_info d ON inf2.token_symbol = d.token_symbol AND inf2.chain = d.chain
        WHERE inf2.narrative = i.narrative
        ORDER BY d.liquidity DESC
        LIMIT 1) AS top_liquidity,
       (SELECT d.price_change_percentage_24h
        FROM smart_money_token_inflow inf2
        JOIN token_dexpool_info d ON inf2.token_symbol = d.token_symbol AND inf2.chain = d.chain
        WHERE inf2.narrative = i.narrative
        ORDER BY d.liquidity DESC
        LIMIT 1) AS price_change_24h
FROM smart_money_token_inflow i
GROUP BY i.narrative
HAVING COUNT(DISTINCT i.token_symbol) > 2;

[User] Finally, only show narratives where the total usd_value exceeds 20000.

[Assistant]
SELECT i.narrative, SUM(i.usd_value) AS total_usd_inflow,
       (SELECT d.token_symbol
        FROM smart_money_token_inflow inf2
        JOIN token_dexpool_info d ON inf2.token_symbol = d.token_symbol AND inf2.chain = d.chain
        WHERE inf2.narrative = i.narrative
        ORDER BY d.liquidity DESC
        LIMIT 1) AS top_liquidity_token,
       (SELECT d.liquidity
        FROM smart_money_token_inflow inf2
        JOIN token_dexpool_info d ON inf2.token_symbol = d.token_symbol AND inf2.chain = d.chain
        WHERE inf2.narrative = i.narrative
        ORDER BY d.liquidity DESC
        LIMIT 1) AS top_liquidity,
       (SELECT d.price_change_percentage_24h
        FROM smart_money_token_inflow inf2
        JOIN token_dexpool_info d ON inf2.token_symbol = d.token_symbol AND inf2.chain = d.chain
        WHERE inf2.narrative = i.narrative
        ORDER BY d.liquidity DESC
        LIMIT 1) AS price_change_24h
FROM smart_money_token_inflow i
GROUP BY i.narrative
HAVING COUNT(DISTINCT i.token_symbol) > 2
   AND SUM(i.usd_value) > 20000;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE token_dexpool_info ( pair_address character varying(512) NOT NULL, -- the id of dexpool token_name character varying(100) NOT NULL, -- the name of the token in the dexpool token_symbol character varying(100) NOT NULL, -- the token's symbol chain text, -- the chain that the dexpool resides price double precision, -- the current price of the token price_change_percentage_1h double precision, -- change in value divided by the absolute price value of the original token price in 1 hour price_change_percentage_6h double precision, -- change in value divided by the absolute price value of the original token price in 6 hours price_change_percentage_24h double precision, -- change in value divided by the absolute price value of the original token price in 24 hours makers_24h double precision, -- the makers of the dex pool in 24 hours volume_24h double precision, -- the trade volume of the dex pool in 24 hours liquidity double precision, -- the liquidity of the dex pool market_cap double precision, -- the market cap of the token trend_rank bigint, -- the rank of token in the dex pool of recent trending, value 1 expresses the most popular token. ,PRIMARY KEY (pair_address, chain) )
CREATE TABLE smart_money_token_performance ( token_address text, token_symbol text, pnl numeric, net_flow numeric, avg_cost numeric, price numeric, realized_ratio numeric, roi numeric, chain text )
  "CREATE TABLE smart_money_token_inflow (",
    "token_address character varying(100) NOT NULL, -- the token's address",
    "token_symbol character varying(100), -- the tokens's symbol",
    "token_amount numeric(38,2), -- the absolute value of the amount if user bought minus  the amount user sold of this token",
    "usd_value numeric(38,2), -- the absolute usd value of the bought token minus sold token",
    "avg_price numeric(38,6), -- the average cost price of user spent on this token",
    "type int, -- the direction of the trade on this token. 1 means buying, 2 means selling",
    "address_amount integer, -- the amount of the user bought this token",
    "narrative character varying(100), -- the category or narrative of the token",
    "chain character varying(100), -- the chain that the token resides",
    ",PRIMARY KEY (token_address, chain)",


[User] Show me all loans (loan_id, loan_type, principal_amount) where the current principal balance is less than 30% of the original principal amount, along with their account_id and status.

[Assistant] SELECT loan_id, loan_type, principal_amount, account_id, status FROM financial_services.loans WHERE current_principal_balance < 0.3 * principal_amount;

[User] Now modify the query to only include active loans (status = 'Active') and sort them by principal_amount in descending order.

[Assistant] SELECT loan_id, loan_type, principal_amount, account_id, status FROM financial_services.loans WHERE current_principal_balance < 0.3 * principal_amount AND status = 'Active' ORDER BY principal_amount DESC;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE financial_services.loans ( loan_id.text, account_id.text, loan_type.text, principal_amount.numeric, current_principal_balance.numeric, interest_rate.numeric, term_months.integer, origination_date.date, maturity_date.date, monthly_payment.numeric, collateral_description.text, status.text )


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

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

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

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

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE smart_money_token_inflow ( token_address character varying(100) NOT NULL, -- the token's address token_symbol character varying(100), -- the tokens's symbol token_amount numeric(38,2), -- the absolute value of the amount if user bought minus  the amount user sold of this token usd_value numeric(38,2), -- the absolute usd value of the bought token minus sold token avg_price numeric(38,6), -- the average cost price of user spent on this token type int, -- the direction of the trade on this token. 1 means buying, 2 means selling address_amount integer, -- the amount of the user bought this token narrative character varying(100), -- the category or narrative of the token chain character varying(100), -- the chain that the token resides ,PRIMARY KEY (token_address, chain) )


[User] Can you show me all prescriptions along with each patient's policy number and insurance plan ID?

[Assistant]
SELECT p.prescription_id, p.patient_id, p.medication_id, pi.policy_number, pi.plan_id
FROM healthcare.prescriptions p
JOIN healthcare.patient_insurance pi ON p.patient_id = pi.patient_id;

[User] Actually, only show prescriptions for patients whose insurance policy is still active today.

[Assistant]
SELECT p.prescription_id, p.patient_id, p.medication_id, pi.policy_number, pi.plan_id
FROM healthcare.prescriptions p
JOIN healthcare.patient_insurance pi ON p.patient_id = pi.patient_id
WHERE pi.effective_date <= CURRENT_DATE AND (pi.expiration_date IS NULL OR pi.expiration_date >= CURRENT_DATE);

[User] Only include those policies marked as primary and order by prescription_date descending.

[Assistant]
SELECT p.prescription_id, p.patient_id, p.medication_id, pi.policy_number, pi.plan_id
FROM healthcare.prescriptions p
JOIN healthcare.patient_insurance pi ON p.patient_id = pi.patient_id
WHERE pi.effective_date <= CURRENT_DATE
  AND (pi.expiration_date IS NULL OR pi.expiration_date >= CURRENT_DATE)
  AND pi.is_primary = TRUE
ORDER BY p.prescription_date DESC;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
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] Find the top 5 employees who have verified the most documents. Display the employee full name and the count of verified documents, ordered by count descending.

[Assistant]
SELECT e.first_name || ' ' || e.last_name AS full_name,
       COUNT(*) AS verified_count
FROM government_services.documents d
JOIN government_services.employees e
  ON d.verified_by_employee_id = e.employee_id
WHERE d.verification_status = 'Verified'
GROUP BY e.first_name, e.last_name
ORDER BY verified_count DESC
LIMIT 5;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE government_services.citizens (
    citizen_id character varying(64) NOT NULL,  -- unique identifier for the citizen
    national_id_number character varying(128) NOT NULL UNIQUE, -- official national identification number
    first_name character varying(100) NOT NULL,
    last_name character varying(100) NOT NULL,
    date_of_birth date NOT NULL,
    gender character varying(20),
    primary_address text NOT NULL, -- full primary residential address
    contact_email character varying(128) UNIQUE,
    contact_phone character varying(32),
    registration_date timestamp NOT NULL, -- when the citizen profile was created
    is_verified boolean DEFAULT false, -- whether identity has been officially verified
    PRIMARY KEY (citizen_id)
)
CREATE TABLE government_services.agencies ( agency_id text, agency_name text, jurisdiction_level text, primary_contact_email text, main_phone_number text, website_url text, established_date date, parent_agency_id text )
CREATE TABLE government_services.applications ( application_id character varying(64) NOT NULL, citizen_id character varying(64) NOT NULL, service_id character varying(64) NOT NULL, submitted_at timestamp NOT NULL, status character varying(50) NOT NULL, last_updated_at timestamp NOT NULL, assigned_employee_id character varying(64), decision_date date, notes text, reference_number character varying(100) UNIQUE, PRIMARY KEY (application_id) )
CREATE TABLE government_services.documents ( document_id text, application_id text, citizen_id text, document_type text, file_reference text, upload_timestamp timestamp, expiry_date date, verification_status text, verified_by_employee_id text, verification_timestamp timestamp )
CREATE TABLE government_services.payments ( payment_id text, application_id text, citizen_id text, service_id text, amount numeric, currency text, payment_method text, payment_provider_reference text, payment_timestamp timestamp, status text, notes text )
CREATE TABLE government_services.employees ( employee_id character varying(64) NOT NULL, agency_id character varying(64) NOT NULL, first_name character varying(100) NOT NULL, last_name character varying(100) NOT NULL, job_title character varying(150) NOT NULL, department character varying(100), work_email character varying(128) NOT NULL UNIQUE, work_phone character varying(32), hire_date date NOT NULL, termination_date date, access_level character varying(50), manager_employee_id character varying(64), PRIMARY KEY (employee_id) )
CREATE TABLE government_services.service_locations (
    location_id character varying(64) NOT NULL, -- unique identifier for the physical location
    agency_id character varying(64) NOT NULL, -- FK to agencies table
    location_name character varying(200), -- e.g., Downtown DMV Office
    address text NOT NULL,
    city character varying(100),
    state character varying(50),
    postal_code character varying(20),
    latitude numeric(9, 6),
    longitude numeric(9, 6),
    operating_hours text, -- description of opening times
    contact_phone character varying(32),
    is_accessible boolean, -- accessibility information (e.g., wheelchair access)
    PRIMARY KEY (location_id)
)
CREATE TABLE government_services.notifications ( notification_id character varying(64) NOT NULL, citizen_id character varying(64) NOT NULL, application_id character varying(64), message_subject character varying(255), message_body text NOT NULL, channel character varying(30) NOT NULL, sent_at timestamp NOT NULL, status character varying(30) NOT NULL, related_entity_type character varying(50), related_entity_id character varying(64), PRIMARY KEY (notification_id) )


[User] List all ERC20 tokens where the price is between $1 and $10, including their names, symbols, and contract addresses.

[Assistant] SELECT tm.name, tm.symbol, tm.contract_address FROM token_metas tm JOIN token_prices_latest tpl ON tm.contract_address = tpl.contract_address WHERE tm.is_erc20 = 1 AND tpl.price BETWEEN 1 AND 10;

[User] I think there's an error in your query - the token_prices_latest table isn't in the schema. Can you modify it to use the token_balances table instead?

[Assistant] SELECT tm.name, tm.symbol, tm.contract_address FROM token_metas tm JOIN token_balances tb ON tm.contract_address = tb.wallet_address WHERE tm.is_erc20 = 1 AND CAST(tb.amount AS decimal) BETWEEN 1 AND 10;

[User] That doesn't seem right either. Let's just get the basic ERC20 token information without price filtering for now.

[Assistant] SELECT name, symbol, contract_address FROM token_metas WHERE is_erc20 = 1 LIMIT 100;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##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 NOT NULL, block_timestamp timestamp(3) NOT NULL, transaction_index integer NOT NULL, transaction_hash varchar(66) NOT NULL, log_index integer NOT NULL, contract_address varchar(42) NOT NULL )
CREATE TABLE erc20_balances ( block_number bigint NOT NULL, contract_address varchar NOT NULL, wallet_address varchar NOT NULL, amount varchar NOT NULL, pk varchar NOT NULL )
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_nfts ( object_id text, status text, collection_type text, package_id text, previous_transaction text, display text, owner text, name text )
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 erc20_approval ( block_number bigint NOT NULL, block_timestamp timestamp(6) NOT NULL, transaction_index integer NOT NULL, transaction_hash varchar NOT NULL, log_index integer NOT NULL, contract_address varchar NOT NULL, pk integer NOT NULL )
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_activities ( block_timestamp timestamp, block_number bigint, tx_index integer, tx_hash varchar, log_index integer, type varchar, tick varchar, id varchar, amt decimal, from_address varchar, to_address varchar )
CREATE TABLE mud_holesky_redstone ( address varchar NOT NULL, table_id varchar NOT NULL, key_bytes varchar NOT NULL, key0 varchar NOT NULL, key1 varchar NOT NULL, static_data varchar NOT NULL, encoded_lengths varchar NOT NULL, dynamic_data varchar NOT NULL, is_deleted boolean NOT NULL, block_number bigint NOT NULL, log_index bigint NOT NULL )
CREATE TABLE token_balances_bitcoin ( block_number bigint, block_timestamp timestamp, tick varchar, wallet_address varchar, total_supply varchar, amount varchar )
CREATE TABLE token_info_bitcoin ( block_timestamp timestamp, block_number bigint, tx_index integer, tx_hash varchar, tick varchar, max_supply decimal, lim decimal, wlim decimal, dec integer, creator varchar )
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 NOT NULL, -- Block number containing the transaction
    block_timestamp timestamp(3) NOT NULL, -- Block timestamp containing the transaction
    tick varchar(20) NOT NULL, -- Ticker: Identifier of the inscription
    wallet_address varchar(42) NOT NULL, -- Address of owner
    total_supply decimal(38,0) NOT NULL, -- Max supply: Set max supply of the inscription
    amount decimal(38,0) NOT NULL  -- The balance of wallet balance at the corresponding block height
)
CREATE TABLE token_info_avalanche ( block_timestamp timestamp, block_number bigint, tx_index integer, tx_hash varchar, tick varchar, max_supply decimal, lim decimal, wlim decimal, dec integer, creator varchar, minted decimal, holders decimal, txs decimal, updated_timestamp timestamp, completed_timestamp timestamp, id varchar )


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

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

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

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

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

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

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE government_services.citizens (
    citizen_id character varying(64) NOT NULL,  -- unique identifier for the citizen
    national_id_number character varying(128) NOT NULL UNIQUE, -- official national identification number
    first_name character varying(100) NOT NULL,
    last_name character varying(100) NOT NULL,
    date_of_birth date NOT NULL,
    gender character varying(20),
    primary_address text NOT NULL, -- full primary residential address
    contact_email character varying(128) UNIQUE,
    contact_phone character varying(32),
    registration_date timestamp NOT NULL, -- when the citizen profile was created
    is_verified boolean DEFAULT false, -- whether identity has been officially verified
    PRIMARY KEY (citizen_id)
)
CREATE TABLE government_services.agencies ( agency_id.text, agency_name.text, jurisdiction_level.text, primary_contact_email.text, main_phone_number.text, website_url.text, established_date.date, parent_agency_id.text )
CREATE TABLE government_services.services ( service_id text PRIMARY KEY, agency_id text, service_name text, description text, category text, eligibility_criteria text, standard_fee numeric, average_processing_time_days int, is_active boolean, online_application_url text )
CREATE TABLE government_services.applications ( application_id character varying(64) NOT NULL, citizen_id character varying(64) NOT NULL, service_id character varying(64) NOT NULL, submitted_at timestamp NOT NULL, status character varying(50) NOT NULL, last_updated_at timestamp NOT NULL, assigned_employee_id character varying(64), decision_date date, notes text, reference_number character varying(100) UNIQUE, PRIMARY KEY (application_id) )
CREATE TABLE government_services.documents ( document_id.text, application_id.text, citizen_id.text, document_type.text, file_reference.text, upload_timestamp.timestamp, expiry_date.date, verification_status.text, verified_by_employee_id.text, verification_timestamp.timestamp )
CREATE TABLE government_services.payments ( payment_id text, application_id text, citizen_id text, service_id text, amount numeric, currency text, payment_method text, payment_provider_reference text, payment_timestamp timestamp, status text, notes text )
CREATE TABLE government_services.service_locations (
    location_id character varying(64) NOT NULL, -- unique identifier for the physical location
    agency_id character varying(64) NOT NULL, -- FK to agencies table
    location_name character varying(200), -- e.g., Downtown DMV Office
    address text NOT NULL,
    city character varying(100),
    state character varying(50),
    postal_code character varying(20),
    latitude numeric(9, 6),
    longitude numeric(9, 6),
    operating_hours text, -- description of opening times
    contact_phone character varying(32),
    is_accessible boolean, -- accessibility information (e.g., wheelchair access)
    PRIMARY KEY (location_id)
)
CREATE TABLE government_services.notifications ( notification_id text PRIMARY KEY, citizen_id text, application_id text, message_subject text, message_body text, channel text, sent_at timestamp, status text, related_entity_type text, related_entity_id text )


[User] Show me all hashtag IDs and their tag names that were created after June 10, 2024 and whose tag names contain the word 'dev'.

[Assistant] SELECT hashtag_id, tag_name FROM social_media.hashtags WHERE created_at > '2024-06-10' AND tag_name ILIKE '%dev%';

[User] Can you also include the creation timestamp and order the results by created_at ascending?

[Assistant] SELECT hashtag_id, tag_name, created_at FROM social_media.hashtags WHERE created_at > '2024-06-10' AND tag_name ILIKE '%dev%' ORDER BY created_at ASC;

[User] Actually, only show hashtags where the tag name starts with the letter 'D'.

[Assistant] SELECT hashtag_id, tag_name, created_at FROM social_media.hashtags WHERE created_at > '2024-06-10' AND tag_name ILIKE 'D%' ORDER BY created_at ASC;

[User] Limit the results to the top 8 hashtags.

[Assistant] SELECT hashtag_id, tag_name, created_at FROM social_media.hashtags WHERE created_at > '2024-06-10' AND tag_name ILIKE 'D%' ORDER BY created_at ASC LIMIT 8;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE social_media.hashtags ( hashtag_id text, tag_name text, created_at timestamp )


[User] List the medication_name and manufacturer for all medications where the description is null or an empty string.

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

[User] Now, refine the query to only include medications whose ndc_code starts with '5'.

[Assistant] SELECT medication_name, manufacturer FROM healthcare.medications WHERE (description IS NULL OR description = '') AND ndc_code LIKE '5%';

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##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 character varying(64) NOT NULL,  -- unique identifier for the doctor
    first_name character varying(100) NOT NULL, -- doctor's first name
    last_name character varying(100) NOT NULL, -- doctor's last name
    specialty character varying(100) NOT NULL, -- doctor's medical specialty
    license_number character varying(50) UNIQUE NOT NULL, -- doctor's medical license number
    phone_number character varying(20), -- doctor's contact phone
    email character varying(128) UNIQUE, -- doctor's contact email
    hospital_affiliation_id character varying(64), -- FK to hospitals table (optional)
    created_at timestamp with time zone NOT NULL DEFAULT current_timestamp,
    updated_at timestamp with time zone NOT NULL DEFAULT current_timestamp,
    PRIMARY KEY (doctor_id)
)
CREATE TABLE healthcare.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.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 character varying(64) NOT NULL, -- unique identifier for the medication type
    medication_name character varying(255) NOT NULL, -- common or brand name
    generic_name character varying(255), -- generic chemical name
    manufacturer character varying(100), -- drug manufacturer
    ndc_code character varying(20) UNIQUE, -- National Drug Code (optional but useful)
    description text, -- description of the medication
    PRIMARY KEY (medication_id)
)
CREATE TABLE healthcare.prescriptions (
    prescription_id character varying(64) NOT NULL, -- unique identifier for the prescription
    record_id character varying(64) NOT NULL, -- FK linking to the medical record where it was prescribed
    patient_id character varying(64) NOT NULL, -- FK to patients table
    doctor_id character varying(64) NOT NULL, -- FK to prescribing doctor
    medication_id character varying(64) NOT NULL, -- FK to medications table
    dosage character varying(100) NOT NULL, -- e.g., '100mg', '1 tablet'
    frequency character varying(100) NOT NULL, -- e.g., 'Once daily', 'Twice a day with meals'
    route character varying(50), -- e.g., 'Oral', 'Topical', 'Intravenous'
    start_date date NOT NULL, -- date prescription begins
    end_date date, -- date prescription ends (if applicable)
    quantity_dispensed numeric(10,2), -- amount dispensed (e.g., number of tablets)
    refills_allowed integer NOT NULL DEFAULT 0, -- number of allowed refills
    prescription_date timestamp with time zone NOT NULL DEFAULT current_timestamp,
    PRIMARY KEY (prescription_id)
)
CREATE TABLE healthcare.insurance_plans (
    plan_id character varying(64) NOT NULL, -- unique identifier for the insurance plan
    plan_name character varying(200) NOT NULL, -- name of the insurance plan
    insurance_provider character varying(100) NOT NULL, -- name of the insurance company
    plan_type character varying(50), -- e.g., PPO, HMO, EPO
    contact_phone character varying(20), -- provider contact number
    website character varying(255), -- provider website
    PRIMARY KEY (plan_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] Show me all active electric vehicles along with their make, model, and license plate, ordered by acquisition date with the newest first.

[Assistant] SELECT vehicle_id, make, model, license_plate, acquisition_date FROM transportation.vehicles WHERE status = 'active' AND fuel_type = 'electric' ORDER BY acquisition_date DESC;

[User] Now include the depot_id for these vehicles and filter to only show vehicles acquired in the last 2 years.

[Assistant] SELECT vehicle_id, make, model, license_plate, acquisition_date, depot_id FROM transportation.vehicles WHERE status = 'active' AND fuel_type = 'electric' AND acquisition_date >= CURRENT_DATE - INTERVAL '2 years' ORDER BY acquisition_date DESC;

[User] Can you also include the vehicle's capacity and order the results by capacity in descending order?

[Assistant] SELECT vehicle_id, make, model, license_plate, acquisition_date, depot_id, capacity FROM transportation.vehicles WHERE status = 'active' AND fuel_type = 'electric' AND acquisition_date >= CURRENT_DATE - INTERVAL '2 years' ORDER BY capacity DESC;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE transportation.vehicles ( vehicle_id character varying(64) NOT NULL, license_plate character varying(32) NOT NULL UNIQUE, vin character varying(17) UNIQUE, make character varying(64) NOT NULL, model character varying(64) NOT NULL, year integer NOT NULL, type character varying(32) NOT NULL, capacity integer, fuel_type character varying(32) NOT NULL, status character varying(32) NOT NULL, depot_id character varying(64), acquisition_date date, PRIMARY KEY (vehicle_id) )


[User] Show me each service order along with the next order placed by the same guest, including both order IDs and the time difference in minutes between the two orders.

[Assistant]
SELECT a.order_id,
       b.order_id AS next_order_id,
       EXTRACT(EPOCH FROM (b.order_timestamp - a.order_timestamp)) / 60 AS diff_minutes
FROM hospitality_technology.service_orders a
JOIN hospitality_technology.service_orders b
  ON a.guest_id = b.guest_id
 AND b.order_timestamp > a.order_timestamp;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE hospitality_technology.service_orders ( order_id.text, reservation_id.text, guest_id.text, service_id.text, staff_id_ordered.text, staff_id_delivered.text, order_timestamp.timestamp, delivery_timestamp.timestamp, quantity.integer, unit_price.numeric, total_price.numeric, status.text, notes.text, bill_id.text )


[User] Find pairs of citizens who share the same gender but registered in different years. Show each citizen's first and last name along with their registration year.

[Assistant]
SELECT c1.first_name AS first_name_1,
       c1.last_name  AS last_name_1,
       EXTRACT(YEAR FROM c1.registration_date) AS reg_year_1,
       c2.first_name AS first_name_2,
       c2.last_name  AS last_name_2,
       EXTRACT(YEAR FROM c2.registration_date) AS reg_year_2
FROM government_services.citizens c1
JOIN government_services.citizens c2
  ON c1.gender = c2.gender
 AND EXTRACT(YEAR FROM c1.registration_date) <> EXTRACT(YEAR FROM c2.registration_date)
 AND c1.citizen_id < c2.citizen_id;

[User] Exclude any pairs where either citizen is not verified.

[Assistant]
SELECT c1.first_name AS first_name_1,
       c1.last_name  AS last_name_1,
       EXTRACT(YEAR FROM c1.registration_date) AS reg_year_1,
       c2.first_name AS first_name_2,
       c2.last_name  AS last_name_2,
       EXTRACT(YEAR FROM c2.registration_date) AS reg_year_2
FROM government_services.citizens c1
JOIN government_services.citizens c2
  ON c1.gender = c2.gender
 AND EXTRACT(YEAR FROM c1.registration_date) <> EXTRACT(YEAR FROM c2.registration_date)
 AND c1.citizen_id < c2.citizen_id
WHERE c1.is_verified = TRUE
  AND c2.is_verified = TRUE;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE government_services.citizens ( citizen_id text, national_id_number text, first_name text, last_name text, date_of_birth date, gender text, primary_address text, contact_email text, contact_phone text, registration_date timestamp, is_verified boolean )


[User] How many appointments are scheduled to start tomorrow?

[Assistant] SELECT count(*) FROM government_services.appointments WHERE DATE(scheduled_start_time) = CURRENT_DATE + INTERVAL '1 day'

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE government_services.appointments ( appointment_id text PRIMARY KEY, citizen_id text, employee_id text, location_id text, service_id text, scheduled_start_time timestamp, scheduled_end_time timestamp, purpose text, status text, booking_method text, created_at timestamp, notes text )


[User] Show me the top 3 smart money addresses by profit across all chains, along with their most profitable token and chain information.

[Assistant]
SELECT address, profit, most_profit_token, chain
FROM smart_money_profit
ORDER BY profit DESC
LIMIT 3;

[User] Actually, I only want to see addresses from Ethereum chain with ROI over 30%.

[Assistant]
SELECT address, profit, most_profit_token, roi
FROM smart_money_profit
WHERE chain = 'Ethereum' AND roi > 30
ORDER BY profit DESC
LIMIT 3;

[User] Can you add their realized profit ratio and filter to only show results with profit over $100,000?

[Assistant]
SELECT address, profit, most_profit_token, roi, realized_ratio
FROM smart_money_profit
WHERE chain = 'Ethereum' AND roi > 30 AND profit > 100000
ORDER BY profit DESC
LIMIT 3;

[User] Now order these results by ROI in descending order instead of profit.

[Assistant]
SELECT address, profit, most_profit_token, roi, realized_ratio
FROM smart_money_profit
WHERE chain = 'Ethereum' AND roi > 30 AND profit > 100000
ORDER BY roi DESC
LIMIT 3;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE project_fundraising_record ( id character varying(32) NOT NULL,  -- fundraising record id project_id character varying(32) NOT NULL, -- the invested project's id project_name character varying(128) NOT NULL, -- name of the invested project rounds_name character varying(32), -- name of the fundraising round investment_value numeric(38,14), -- amount of the fundraising in USD investment_date character varying(128), -- the date of the investment happened introduction character varying(128), -- the introduction of the invested project valuation numeric(38,14), -- the valuation of the project in USD when invested )
CREATE TABLE narrative_info ( narrative character varying(512) NOT NULL, -- the id of narrative top_3_coins text, -- the top 3 tokens in the narrative price_change_percentage_1h double precision, -- change in value divided by the absolute price value of the original token price in 1 hour in the narrative price_change_percentage_24h double precision, -- change in value divided by the absolute price value of the original token price in 24 hours in the narrative price_change_percentage_7d double precision, -- change in value divided by the absolute price value of the original token price in 7 days in the narrative market_cap double precision, -- the market cap of the narrative volume_24h double precision, -- the trade volume of the narrative trend_rank bigint, -- the trending rank of the narrative, value 1 expresses the most popular narrative token_num bigint, -- total token number in the narrative ,PRIMARY KEY (narrative) )
CREATE TABLE smart_money_profit ( address character varying(100) NOT NULL, -- the user's address rank INT, -- the rank of the address in trade performance, value 1 expresses the best address. profit numeric(38,6), -- the profit user made in a month roi numeric(38,2), -- the roi of the user in a month realized_ratio numeric(38,2), -- the percentage of the user's realized profit most_profit_token character varying(100), -- the token symbol of the user's most profitable trade last_trade_time character varying(100), -- the last trade time of the user chain character varying(100), -- the chain that the address resides PRIMARY KEY (address, chain) )


[User] Which projects raised funds in January 2022?

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

[User] Please also show their introductions.

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

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE project_fundraising_record ( id.text, project_id.text, project_name.text, rounds_name.text, investment_value.numeric, investment_date.text, introduction.text, valuation.numeric )


[User] Retrieve the total number of agents managed by each manager, showing the manager_id and the count.

[Assistant] SELECT manager_id, COUNT(*) FROM insurance.agents GROUP BY manager_id;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE insurance.agents ( agent_id.text, first_name.text, last_name.text, agency_name.text, license_number.text, license_state.text, contact_email.text, contact_phone.text, hire_date.date, termination_date.date, status.text, commission_rate.numeric, manager_id.text )


[User] How many medications does each manufacturer have?

[Assistant]
SELECT manufacturer, COUNT(*) AS med_count
FROM healthcare.medications
GROUP BY manufacturer;

[User] Only include manufacturers with more than 10 medications.

[Assistant]
SELECT manufacturer, COUNT(*) AS med_count
FROM healthcare.medications
GROUP BY manufacturer
HAVING COUNT(*) > 10;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE healthcare.medications ( medication_id character varying(64) NOT NULL, medication_name character varying(255) NOT NULL, generic_name character varying(255), manufacturer character varying(100), ndc_code character varying(20) UNIQUE, description text, PRIMARY KEY (medication_id) )


[User] Retrieve, for each room type, the total number of services offered by its property, including the property_name, type_name, and service_count.

[Assistant]
SELECT p.property_name,
       rt.type_name,
       COUNT(s.service_id) AS service_count
FROM hospitality_technology.room_types rt
JOIN hospitality_technology.properties p ON rt.property_id = p.property_id
LEFT JOIN hospitality_technology.services s ON rt.property_id = s.property_id
GROUP BY p.property_name, rt.type_name;

[User] Filter to only count services that are currently available.

[Assistant]
SELECT p.property_name,
       rt.type_name,
       COUNT(s.service_id) AS service_count
FROM hospitality_technology.room_types rt
JOIN hospitality_technology.properties p ON rt.property_id = p.property_id
JOIN hospitality_technology.services s ON rt.property_id = s.property_id
  AND s.is_available = true
GROUP BY p.property_name, rt.type_name;

[User] Also only show room types with service_count greater than 3 and order by service_count descending.

[Assistant]
SELECT p.property_name,
       rt.type_name,
       COUNT(s.service_id) AS service_count
FROM hospitality_technology.room_types rt
JOIN hospitality_technology.properties p ON rt.property_id = p.property_id
JOIN hospitality_technology.services s ON rt.property_id = s.property_id
  AND s.is_available = true
GROUP BY p.property_name, rt.type_name
HAVING COUNT(s.service_id) > 3
ORDER BY service_count DESC;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE hospitality_technology.properties (
    property_id character varying(64) NOT NULL,  -- unique identifier for the property (hotel, resort, etc.)
    property_name character varying(255) NOT NULL, -- name of the property
    address_line1 character varying(255) NOT NULL, -- primary address line
    address_line2 character varying(255), -- secondary address line
    city character varying(100) NOT NULL, -- city
    state_province character varying(100), -- state or province
    postal_code character varying(20) NOT NULL, -- zip or postal code
    country_code character varying(3) NOT NULL, -- ISO country code (e.g., USA, CAN)
    phone_number character varying(30), -- main contact phone
    email_address character varying(255), -- main contact email
    property_type character varying(50) NOT NULL, -- e.g., Hotel, Resort, B&B, Motel
    star_rating numeric(2,1), -- star rating (e.g., 4.5)
    timezone character varying(64) NOT NULL, -- IANA timezone ID (e.g., America/New_York)
    manager_staff_id character varying(64), -- FK to staff table for the general manager
    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 (property_id)
)
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 character varying(64) NOT NULL, first_name character varying(100) NOT NULL, last_name character varying(100) NOT NULL, email character varying(255) UNIQUE, phone_number character varying(30), date_of_birth date, address_line1 character varying(255), city character varying(100), state_province character varying(100), postal_code character varying(20), country_code character varying(3), preferences text, loyalty_member_id character varying(64) UNIQUE, communication_consent boolean DEFAULT true, created_at timestamp with time zone NOT NULL DEFAULT current_timestamp, updated_at timestamp with time zone NOT NULL DEFAULT current_timestamp, PRIMARY KEY (guest_id) )
CREATE TABLE hospitality_technology.reservations ( reservation_id text, property_id text, guest_id text, room_id text, room_type_id text, check_in_date date, check_out_date date, actual_check_in_ts timestamp, actual_check_out_ts timestamp, num_adults integer, num_children integer, status text, booking_source text, rate_plan_id text, total_amount numeric, amount_paid numeric, special_requests text, created_at timestamp, updated_at timestamp )
CREATE TABLE hospitality_technology.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, 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 character varying(64) NOT NULL,  -- unique identifier for the payment transaction
    reservation_id character varying(64), -- FK to reservations (if payment is for a stay)
    guest_id character varying(64) NOT NULL, -- FK to guests (who paid)
    bill_id character varying(64), -- FK to bills/invoices this payment applies to
    amount numeric(12,2) NOT NULL, -- amount of the payment
    currency_code character varying(3) NOT NULL, -- ISO currency code (e.g., USD, EUR)
    payment_method character varying(50) NOT NULL, -- e.g., CreditCard, Cash, BankTransfer, Points, Voucher
    card_type character varying(50), -- e.g., Visa, MasterCard, Amex (if CC)
    card_last_four character varying(4), -- last 4 digits of CC (if CC)
    transaction_ref character varying(128), -- reference ID from payment gateway or processor
    payment_timestamp timestamp with time zone NOT NULL DEFAULT current_timestamp, -- when the payment occurred
    status character varying(50) NOT NULL, -- e.g., Pending, Succeeded, Failed, Refunded, Disputed
    staff_id_processed character varying(64), -- FK to staff (who processed the payment)
    notes text, -- notes about the payment
    PRIMARY KEY (payment_id),
    FOREIGN KEY (reservation_id) REFERENCES hospitality_technology.reservations(reservation_id),
    FOREIGN KEY (guest_id) REFERENCES hospitality_technology.guests(guest_id),
    FOREIGN KEY (staff_id_processed) REFERENCES hospitality_technology.staff(staff_id)
)


[User] List the first and last names of employees and the number of services offered by their agency.

[Assistant]
SELECT e.first_name, e.last_name, COUNT(s.service_id) AS service_count
FROM government_services.employees e
LEFT JOIN government_services.services s ON e.agency_id = s.agency_id
GROUP BY e.employee_id, e.first_name, e.last_name;

[User] Include only employees whose agency offers more than 3 services.

[Assistant]
SELECT e.first_name, e.last_name, COUNT(s.service_id) AS service_count
FROM government_services.employees e
LEFT JOIN government_services.services s ON e.agency_id = s.agency_id
GROUP BY e.employee_id, e.first_name, e.last_name
HAVING COUNT(s.service_id) > 3;

[User] Add the agency name to the result.

[Assistant]
SELECT e.first_name, e.last_name, ag.agency_name, COUNT(s.service_id) AS service_count
FROM government_services.employees e
JOIN government_services.agencies ag ON e.agency_id = ag.agency_id
LEFT JOIN government_services.services s ON e.agency_id = s.agency_id
GROUP BY e.employee_id, e.first_name, e.last_name, ag.agency_name
HAVING COUNT(s.service_id) > 3;

[User] Now, only show services that are currently active in the count.

[Assistant]
SELECT e.first_name, e.last_name, ag.agency_name, COUNT(s.service_id) AS active_service_count
FROM government_services.employees e
JOIN government_services.agencies ag ON e.agency_id = ag.agency_id
LEFT JOIN government_services.services s ON e.agency_id = s.agency_id AND s.is_active = TRUE
GROUP BY e.employee_id, e.first_name, e.last_name, ag.agency_name
HAVING COUNT(s.service_id) > 3;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE government_services.agencies ( agency_id character varying(64) NOT NULL, agency_name character varying(255) NOT NULL, jurisdiction_level character varying(50) NOT NULL, primary_contact_email character varying(128), main_phone_number character varying(32), website_url character varying(255), established_date date, parent_agency_id character varying(64), PRIMARY KEY (agency_id) )
CREATE TABLE government_services.services (
    service_id character varying(64) NOT NULL, -- unique identifier for the service
    agency_id character varying(64) NOT NULL, -- FK to agencies table
    service_name character varying(255) NOT NULL, -- name of the service (e.g., Driver's License Renewal)
    description text,
    category character varying(100), -- e.g., Licensing, Benefits, Taxation, Permits
    eligibility_criteria text, -- description of who is eligible
    standard_fee numeric(10, 2) DEFAULT 0.00, -- typical fee for the service
    average_processing_time_days integer, -- estimated processing time
    is_active boolean DEFAULT true, -- whether the service is currently offered
    online_application_url character varying(255),
    PRIMARY KEY (service_id)
)
CREATE TABLE government_services.applications (
    application_id character varying(64) NOT NULL, -- unique identifier for the application
    citizen_id character varying(64) NOT NULL, -- FK to citizens table
    service_id character varying(64) NOT NULL, -- FK to services table
    submitted_at timestamp NOT NULL, -- time the application was submitted
    status character varying(50) NOT NULL, -- e.g., Submitted, Processing, Approved, Rejected, Pending Info
    last_updated_at timestamp NOT NULL, -- time the status or details last changed
    assigned_employee_id character varying(64), -- FK to employees table (optional)
    decision_date date, -- date when a final decision was made
    notes text, -- internal notes or citizen-provided comments
    reference_number character varying(100) UNIQUE, -- publicly visible reference number
    PRIMARY KEY (application_id)
)
CREATE TABLE government_services.documents ( document_id text PRIMARY KEY, application_id text, citizen_id text, document_type text, file_reference text, upload_timestamp timestamp, expiry_date date, verification_status text, verified_by_employee_id text, verification_timestamp timestamp )
CREATE TABLE government_services.employees (
    employee_id character varying(64) NOT NULL, -- unique identifier for the government employee
    agency_id character varying(64) NOT NULL, -- FK to agencies table
    first_name character varying(100) NOT NULL,
    last_name character varying(100) NOT NULL,
    job_title character varying(150) NOT NULL,
    department character varying(100),
    work_email character varying(128) NOT NULL UNIQUE,
    work_phone character varying(32),
    hire_date date NOT NULL,
    termination_date date, -- null if currently employed
    access_level character varying(50), -- Role or permission level
    manager_employee_id character varying(64), -- FK to self for reporting structure
    PRIMARY KEY (employee_id)
)
CREATE TABLE government_services.appointments ( appointment_id character varying(64) NOT NULL, citizen_id character varying(64) NOT NULL, employee_id character varying(64), location_id character varying(64), service_id character varying(64), scheduled_start_time timestamp NOT NULL, scheduled_end_time timestamp, purpose text NOT NULL, status character varying(30) NOT NULL, booking_method character varying(50), created_at timestamp NOT NULL, notes text, PRIMARY KEY (appointment_id) )


[User] Now, sort the results by the date opened, oldest first, and show only the top 10.

[Assistant] SELECT case_name, case_number, date_opened FROM legal_services.cases WHERE lead_lawyer_id = 'lawyer_abc' AND status = 'Open' AND case_type = 'Criminal' ORDER BY date_opened ASC LIMIT 10;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE legal_services.cases ( case_id.text, case_number.text, case_name.text, client_id.text, lead_lawyer_id.text, case_type.text, status.text, date_opened.timestamp, date_closed.timestamp, description.text, court_jurisdiction.text )


[User] List all medical record IDs and the record date for records created by doctors specializing in 'Gastroenterology'.

[Assistant] SELECT mr.record_id, mr.record_date FROM healthcare.medical_records mr JOIN healthcare.doctors d ON mr.doctor_id = d.doctor_id WHERE d.specialty = 'Gastroenterology';

[User] Could you also include the patient's first and last name for these records?

[Assistant] SELECT mr.record_id, mr.record_date, p.first_name, p.last_name FROM healthcare.medical_records mr JOIN healthcare.doctors d ON mr.doctor_id = d.doctor_id JOIN healthcare.patients p ON mr.patient_id = p.patient_id WHERE d.specialty = 'Gastroenterology';

[User] Now, only show records for male patients.

[Assistant] SELECT mr.record_id, mr.record_date, p.first_name, p.last_name FROM healthcare.medical_records mr JOIN healthcare.doctors d ON mr.doctor_id = d.doctor_id JOIN healthcare.patients p ON mr.patient_id = p.patient_id WHERE d.specialty = 'Gastroenterology' AND p.gender = 'Male';

[User] Additionally, restrict the results to medical records that have at least one associated diagnosis with status 'Resolved'.

[Assistant] SELECT DISTINCT mr.record_id, mr.record_date, p.first_name, p.last_name FROM healthcare.medical_records mr JOIN healthcare.doctors d ON mr.doctor_id = d.doctor_id JOIN healthcare.patients p ON mr.patient_id = p.patient_id JOIN healthcare.diagnoses diag ON mr.record_id = diag.record_id WHERE d.specialty = 'Gastroenterology' AND p.gender = 'Male' AND diag.status = 'Resolved';

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##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.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.medical_records ( record_id character varying(64) NOT NULL, patient_id character varying(64) NOT NULL, appointment_id character varying(64) UNIQUE, doctor_id character varying(64) NOT NULL, record_date timestamp with time zone NOT NULL, chief_complaint text, present_illness_history text, past_medical_history text, physical_examination_notes text, assessment text, treatment_plan text, vitals jsonb, created_at timestamp with time zone NOT NULL DEFAULT current_timestamp, PRIMARY KEY (record_id) )
CREATE TABLE healthcare.diagnoses ( diagnosis_id text PRIMARY KEY, 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 character varying(64) NOT NULL, record_id character varying(64) NOT NULL, patient_id character varying(64) NOT NULL, doctor_id character varying(64) NOT NULL, medication_id character varying(64) NOT NULL, dosage character varying(100) NOT NULL, frequency character varying(100) NOT NULL, route character varying(50), start_date date NOT NULL, end_date date, quantity_dispensed numeric(10,2), refills_allowed integer NOT NULL DEFAULT 0, prescription_date timestamp with time zone NOT NULL DEFAULT current_timestamp, PRIMARY KEY (prescription_id) )
CREATE TABLE healthcare.insurance_plans ( plan_id character varying(64) NOT NULL, plan_name character varying(200) NOT NULL, insurance_provider character varying(100) NOT NULL, plan_type character varying(50), contact_phone character varying(20), website character varying(255), PRIMARY KEY (plan_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 all insurance products that have no active policies currently.

[Assistant] SELECT ip.product_id, ip.product_name, ip.product_type FROM insurance.insurance_products ip LEFT JOIN insurance.policies p ON ip.product_id = p.product_id AND p.status = 'Active' WHERE p.policy_id IS NULL AND ip.is_active = true;

[User] Now include only products that were created in the last year.

[Assistant] SELECT ip.product_id, ip.product_name, ip.product_type FROM insurance.insurance_products ip LEFT JOIN insurance.policies p ON ip.product_id = p.product_id AND p.status = 'Active' WHERE p.policy_id IS NULL AND ip.is_active = true AND ip.created_at >= CURRENT_DATE - INTERVAL '1 year';

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE insurance.customers ( customer_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, ssn_hash character varying(128), address_line1 character varying(255) NOT NULL, address_line2 character varying(255), city character varying(100) NOT NULL, state character varying(50) NOT NULL, zip_code character varying(20) NOT NULL, country character varying(50) NOT NULL DEFAULT 'USA', phone_number character varying(30), email character varying(128) UNIQUE, created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, updated_at timestamp, status character varying(20) NOT NULL DEFAULT 'Active', PRIMARY KEY (customer_id) )
CREATE TABLE insurance.policies ( policy_id character varying(64) NOT NULL, customer_id character varying(64) NOT NULL, product_id character varying(64) NOT NULL, agent_id character varying(64), policy_number character varying(100) NOT NULL UNIQUE, start_date date NOT NULL, end_date date NOT NULL, premium_amount numeric(12, 2) NOT NULL, coverage_limit numeric(15, 2) NOT NULL, deductible numeric(10, 2) NOT NULL, status character varying(30) NOT NULL, issued_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, 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 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.claim_documents ( document_id character varying(64) NOT NULL, claim_id character varying(64) NOT NULL, document_type character varying(50) NOT NULL, file_name character varying(255) NOT NULL, file_path character varying(512) NOT NULL, file_size_bytes integer, mime_type character varying(100), uploaded_by character varying(64), uploaded_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, description text, PRIMARY KEY (document_id) )


[User] What is the detailed repair history for train number T5678?

[Assistant] I'm sorry, but I can't provide the detailed repair history for train number T5678 as this information is not available in the current database table. The table only includes basic information such as train ID, model, manufacturer, capacity, status, and maintenance dates. For repair history, you may need to consult a different database or department.

System:
You are an SQL statement expert and you can refuse the user's question if the question is not related to the table structure. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE train_station_management.trains ( train_id text, train_number text, model text, manufacturer text, year_manufactured integer, capacity integer, status text, last_maintenance_date date, next_maintenance_date date )


[User] Give me the total number of doctors for each specialty.

[Assistant]
SELECT specialty, COUNT(*) AS doctor_count
FROM healthcare.doctors
GROUP BY specialty;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE healthcare.doctors ( doctor_id text, first_name text, last_name text, specialty text, license_number text, phone_number text, email text, hospital_affiliation_id text, created_at timestamp, updated_at timestamp )


[User] Show me all smart contracts created by addresses that have created more than 3 contracts, along with the count of contracts each creator has made.

[Assistant] SELECT creator_address, COUNT(*) AS contract_count FROM blockchain.smart_contracts GROUP BY creator_address HAVING COUNT(*) > 3;

[User] Now filter these results to only show contracts created in the last 6 months.

[Assistant] SELECT sc.creator_address, COUNT(*) AS contract_count FROM blockchain.smart_contracts sc WHERE sc.timestamp >= NOW() - INTERVAL '6 months' GROUP BY sc.creator_address HAVING COUNT(*) > 3;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE blockchain.smart_contracts ( contract_id text PRIMARY KEY, creator_address text, code text, timestamp timestamp )


[User] List all cancelled policies with their cancellation reasons and premium amounts.

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

[User] Now show only policies that were cancelled within 3 months of their start date.

[Assistant] SELECT policy_id, policy_number, cancellation_reason, premium_amount, start_date, cancellation_date FROM insurance.policies WHERE status = 'Cancelled' AND cancellation_date <= start_date + INTERVAL '3 months';

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE insurance.policies (
    policy_id character varying(64) NOT NULL, -- unique identifier for the policy
    customer_id character varying(64) NOT NULL, -- identifier for the policyholder (FK to customers)
    product_id character varying(64) NOT NULL, -- identifier for the insurance product (FK to insurance_products)
    agent_id character varying(64), -- identifier for the agent who sold the policy (FK to agents)
    policy_number character varying(100) NOT NULL UNIQUE, -- customer-facing policy number
    start_date date NOT NULL, -- date the policy coverage begins
    end_date date NOT NULL, -- date the policy coverage ends
    premium_amount numeric(12, 2) NOT NULL, -- total premium for the policy term
    coverage_limit numeric(15, 2) NOT NULL, -- maximum amount covered
    deductible numeric(10, 2) NOT NULL, -- amount customer pays before coverage kicks in
    status character varying(30) NOT NULL, -- e.g., Active, Expired, Cancelled, Pending
    issued_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, -- when the policy was issued
    cancellation_date date,
    cancellation_reason text,
    PRIMARY KEY (policy_id)
)


[User] For each game, show the game title, the total duration of all sessions in seconds, and the average score.

[Assistant] SELECT g.title, SUM(gs.duration_seconds) AS total_duration_seconds, AVG(gs.score) AS average_score FROM gaming_technology.games g JOIN gaming_technology.game_sessions gs ON g.game_id = gs.game_id GROUP BY g.game_id, g.title;

[User] Could you also show the total number of sessions for each game?

[Assistant] SELECT g.title, COUNT(gs.session_id) AS total_sessions, SUM(gs.duration_seconds) AS total_duration_seconds, AVG(gs.score) AS average_score FROM gaming_technology.games g JOIN gaming_technology.game_sessions gs ON g.game_id = gs.game_id GROUP BY g.game_id, g.title;

[User] Filter the results to only include games with more than 100 sessions.

[Assistant] SELECT g.title, COUNT(gs.session_id) AS total_sessions, SUM(gs.duration_seconds) AS total_duration_seconds, AVG(gs.score) AS average_score FROM gaming_technology.games g JOIN gaming_technology.game_sessions gs ON g.game_id = gs.game_id GROUP BY g.game_id, g.title HAVING COUNT(gs.session_id) > 100;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE gaming_technology.games ( game_id.uuid, title.text, developer_id.uuid, publisher_id.uuid, genre.text, release_date.date, description.text, platform.text, engine.text, website.text )
CREATE TABLE gaming_technology.developers ( developer_id uuid PRIMARY KEY, name text, country text, founded_year int, website text, created_at timestamptz )
CREATE TABLE gaming_technology.game_sessions ( session_id uuid PRIMARY KEY, player_id uuid, game_id uuid, server_id uuid, start_time timestamptz, end_time timestamptz, duration_seconds int, score int, session_data jsonb )
CREATE TABLE gaming_technology.achievements (
    achievement_id uuid NOT NULL DEFAULT gen_random_uuid(), -- unique identifier for an achievement definition
    game_id uuid NOT NULL, -- FK linking to the game the achievement belongs to
    name character varying(150) NOT NULL, -- name of the achievement
    description text NOT NULL, -- how to unlock the achievement
    icon_url character varying(255), -- URL for the achievement's icon
    points integer DEFAULT 0, -- points awarded for unlocking (optional)
    hidden boolean DEFAULT false, -- whether the achievement details are hidden until unlocked
    PRIMARY KEY (achievement_id)
    -- FOREIGN KEY (game_id) REFERENCES gaming_technology.games(game_id)
)
CREATE TABLE gaming_technology.player_inventory (
    inventory_id uuid NOT NULL DEFAULT gen_random_uuid(), -- unique identifier for an inventory entry
    player_id uuid NOT NULL, -- FK linking to the player owning the item
    item_id uuid NOT NULL, -- FK linking to the item definition
    quantity integer NOT NULL DEFAULT 1, -- number of items held (for stackable items)
    acquired_at timestamp with time zone NOT NULL DEFAULT CURRENT_TIMESTAMP, -- when the item was acquired
    instance_data jsonb, -- data specific to this instance (e.g., weapon mods, durability)
    PRIMARY KEY (inventory_id),
    -- Optional unique constraint if items are non-stackable or unique instances
    -- UNIQUE (player_id, item_id) -- Use if quantity is always 1
    -- FOREIGN KEY (player_id) REFERENCES gaming_technology.players(player_id),
    -- FOREIGN KEY (item_id) REFERENCES gaming_technology.in_game_items(item_id)
)


[User] Find all customers who have made a premium payment and list their first name, last name, email, and the total amount they have paid across all their payments.

[Assistant] SELECT T1.first_name, T1.last_name, T1.email, SUM(T2.amount_paid) FROM insurance.customers AS T1 JOIN insurance.premium_payments AS T2 ON T1.customer_id = T2.customer_id GROUP BY T1.customer_id, T1.first_name, T1.last_name, T1.email;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##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.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 )