[User] Show all appointments with subject containing 'Review' and their corresponding case_id.

[Assistant]
SELECT appointment_id, subject, case_id
FROM legal_services.appointments
WHERE subject ILIKE '%Review%';

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.invoices ( invoice_id.text, invoice_number.text, client_id.text, case_id.text, issue_date.date, due_date.date, total_amount.numeric, amount_paid.numeric, status.text, payment_date.timestamp, notes.text, created_at.timestamp )
CREATE TABLE legal_services.appointments ( appointment_id.text, client_id.text, lawyer_id.text, case_id.text, start_time.timestamp, end_time.timestamp, location.text, subject.text, notes.text, status.text, created_at.timestamp )


[User] List the first and last name of each citizen along with the city and state of the service location for their agency.

[Assistant]
SELECT c.first_name, c.last_name, sl.city, sl.state
FROM government_services.citizens c
JOIN government_services.payments p ON c.citizen_id = p.citizen_id
JOIN government_services.employees e ON p.application_id IS NOT NULL AND e.agency_id IS NOT NULL
JOIN government_services.service_locations sl ON e.agency_id = sl.agency_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 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 )
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 text, agency_id text, first_name text, last_name text, job_title text, department text, work_email text, work_phone text, hire_date date, termination_date date, access_level text, manager_employee_id text )
CREATE TABLE government_services.service_locations ( location_id text, agency_id text, location_name text, address text, city text, state text, postal_code text, latitude numeric, longitude numeric, operating_hours text, contact_phone text, is_accessible boolean )


[User] Find all documents of type 'Correspondence' uploaded in 2023. Show the document name, upload timestamp, and the name of the case it belongs to.

[Assistant] SELECT T1.document_name, T1.upload_timestamp, T2.case_name FROM legal_services.documents AS T1 JOIN legal_services.cases AS T2 ON T1.case_id = T2.case_id WHERE T1.document_type = 'Correspondence' AND EXTRACT(YEAR FROM T1.upload_timestamp) = 2023;

[User] Now, only show the documents for cases handled by lawyer with ID 'lawyer_001'.

[Assistant] SELECT T1.document_name, T1.upload_timestamp, T2.case_name FROM legal_services.documents AS T1 JOIN legal_services.cases AS T2 ON T1.case_id = T2.case_id WHERE T1.document_type = 'Correspondence' AND EXTRACT(YEAR FROM T1.upload_timestamp) = 2023 AND T2.lead_lawyer_id = 'lawyer_001';

[User] Additionally, include the first and last name of the lawyer who actually uploaded the document, and sort the results by upload timestamp descending.

[Assistant] SELECT T1.document_name, T1.upload_timestamp, T2.case_name, T3.first_name, T3.last_name FROM legal_services.documents AS T1 JOIN legal_services.cases AS T2 ON T1.case_id = T2.case_id JOIN legal_services.lawyers AS T3 ON T1.uploaded_by_lawyer_id = T3.lawyer_id WHERE T1.document_type = 'Correspondence' AND EXTRACT(YEAR FROM T1.upload_timestamp) = 2023 AND T2.lead_lawyer_id = 'lawyer_001' ORDER BY T1.upload_timestamp 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 legal_services.clients ( client_id text PRIMARY KEY, first_name text, last_name text, company_name text, email text UNIQUE, phone text, address text, date_registered timestamp, status text )
CREATE TABLE legal_services.law_firms ( firm_id text PRIMARY KEY, firm_name text, address text, phone text, website text, founded_date date, managing_partner_id text )
CREATE TABLE legal_services.cases ( case_id.text, case_number.text, case_name.text, client_id.text, lead_lawyer_id.text, case_type.text, status.text, date_opened.timestamp, date_closed.timestamp, description.text, court_jurisdiction.text )
CREATE TABLE legal_services.documents (
    document_id character varying(64) NOT NULL,  -- unique identifier for the document
    case_id character varying(64) NOT NULL, -- FK to cases table
    document_name character varying(255) NOT NULL, -- name of the document file
    document_type character varying(100), -- e.g., Pleading, Contract, Evidence, Correspondence
    storage_path text NOT NULL, -- path or reference to the document storage location
    uploaded_by_lawyer_id character varying(64), -- FK to lawyers table (who uploaded it)
    upload_timestamp timestamp NOT NULL, -- time the document was uploaded
    version integer DEFAULT 1, -- document version number
    description text, -- brief description or notes about the document
    PRIMARY KEY (document_id)
)
CREATE TABLE legal_services.appointments (
    appointment_id character varying(64) NOT NULL, -- unique identifier for the appointment
    client_id character varying(64) NOT NULL, -- FK to clients table
    lawyer_id character varying(64) NOT NULL, -- FK to lawyers table
    case_id character varying(64), -- FK to cases table (optional, if related to a specific case)
    start_time timestamp NOT NULL, -- scheduled start date and time
    end_time timestamp NOT NULL, -- scheduled end date and time
    location text, -- location of the meeting (address or virtual link)
    subject character varying(255), -- subject or purpose of the appointment
    notes text, -- additional notes for the appointment
    status character varying(50) NOT NULL, -- e.g., Scheduled, Completed, Canceled, Rescheduled
    created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
    PRIMARY KEY (appointment_id)
)


[User] List all medical records, showing the record ID, record date, and the full name of the doctor who created the record. Include the patient ID as well.

[Assistant] SELECT mr.record_id, mr.record_date, mr.patient_id, d.first_name, d.last_name FROM healthcare.medical_records mr JOIN doctors d ON mr.doctor_id = d.doctor_id;

[User] Refine this to only include records where the chief_complaint is not null or empty and the doctor's specialty is 'Cardiology'.

[Assistant] SELECT mr.record_id, mr.record_date, mr.patient_id, d.first_name, d.last_name FROM healthcare.medical_records mr JOIN doctors d ON mr.doctor_id = d.doctor_id WHERE (mr.chief_complaint IS NOT NULL AND mr.chief_complaint != '') AND d.specialty = 'Cardiology';

[User] Also, sort the results by record_date in descending order and limit the output to the top 10 records.

[Assistant] SELECT mr.record_id, mr.record_date, mr.patient_id, d.first_name, d.last_name FROM healthcare.medical_records mr JOIN doctors d ON mr.doctor_id = d.doctor_id WHERE (mr.chief_complaint IS NOT NULL AND mr.chief_complaint != '') AND d.specialty = 'Cardiology' ORDER BY mr.record_date DESC 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 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)
)


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

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

System:
You are an 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.clients ( client_id character varying(64) NOT NULL, first_name character varying(100) NOT NULL, last_name character varying(100) NOT NULL, company_name character varying(200), email character varying(128) UNIQUE NOT NULL, phone character varying(32), address text, date_registered timestamp NOT NULL, status character varying(32) NOT NULL, PRIMARY KEY (client_id) )
CREATE TABLE legal_services.lawyers ( lawyer_id character varying(64) NOT NULL, first_name character varying(100) NOT NULL, last_name character varying(100) NOT NULL, bar_number character varying(64) UNIQUE NOT NULL, firm_id character varying(64), email character varying(128) UNIQUE NOT NULL, phone character varying(32), specialization text, hire_date timestamp NOT NULL, is_partner boolean DEFAULT false, PRIMARY KEY (lawyer_id) )
CREATE TABLE legal_services.law_firms ( firm_id character varying(64) NOT NULL, firm_name character varying(200) NOT NULL, address text NOT NULL, phone character varying(32), website character varying(255), founded_date date, managing_partner_id character varying(64), PRIMARY KEY (firm_id) )
CREATE TABLE legal_services.cases ( case_id character varying(64) NOT NULL, case_number character varying(100) UNIQUE, case_name text NOT NULL, client_id character varying(64) NOT NULL, lead_lawyer_id character varying(64) NOT NULL, case_type character varying(100) NOT NULL, status character varying(50) NOT NULL, date_opened timestamp NOT NULL, date_closed timestamp, description text, court_jurisdiction character varying(128), PRIMARY KEY (case_id) )
CREATE TABLE legal_services.documents ( document_id character varying(64) NOT NULL, case_id character varying(64) NOT NULL, document_name character varying(255) NOT NULL, document_type character varying(100), storage_path text NOT NULL, uploaded_by_lawyer_id character varying(64), upload_timestamp timestamp NOT NULL, version integer DEFAULT 1, description text, PRIMARY KEY (document_id) )
CREATE TABLE legal_services.time_entries ( entry_id character varying(64) NOT NULL, case_id character varying(64) NOT NULL, lawyer_id character varying(64) NOT NULL, date_worked date NOT NULL, hours_spent numeric(5, 2) NOT NULL CHECK (hours_spent > 0), billing_rate numeric(10, 2) NOT NULL, description text NOT NULL, is_billable boolean DEFAULT true, is_billed boolean DEFAULT false, invoice_id character varying(64), created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, PRIMARY KEY (entry_id) )
CREATE TABLE legal_services.appointments ( appointment_id character varying(64) NOT NULL, client_id character varying(64) NOT NULL, lawyer_id character varying(64) NOT NULL, case_id character varying(64), start_time timestamp NOT NULL, end_time timestamp NOT NULL, location text, subject character varying(255), notes text, status character varying(50) NOT NULL, created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, PRIMARY KEY (appointment_id) )


[User] What is the schedule of trains arriving at platform 1A at station XYZ on December 25th, 2023?

[Assistant] I'm sorry, but I can't provide information about train schedules or specific arrival times as this data is not included in the platform management table. For train schedules, please refer to the train timetable or contact the station's customer service.

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.platforms (
    platform_id character varying(64) NOT NULL, -- Unique identifier for the platform
    station_id character varying(64) NOT NULL, -- Foreign key referencing stations
    platform_number character varying(10) NOT NULL, -- Platform identifier (e.g., '1A', '5')
    track_number character varying(10), -- Associated track number, if different
    status character varying(32) NOT NULL DEFAULT 'Operational', -- e.g., Operational, Maintenance, Closed
    length_meters numeric(8,2), -- Length of the platform in meters
    accessible boolean NOT NULL DEFAULT false, -- Is the platform accessible (e.g., wheelchair)?
    PRIMARY KEY (platform_id),
    FOREIGN KEY (station_id) REFERENCES train_station_management.stations(station_id)
)


[User] List all active SUI coins with status 'exists' in metadata, showing coin_type, symbol, name, balance, and description.

[Assistant]
SELECT sc.coin_type, sm.symbol, sm.name, sc.balance, sm.description
FROM sui_coins sc
JOIN sui_coins_metadata sm ON sc.coin_type = sm.coin_type
WHERE sm.status = 'exists';

[User] Limit to coins where balance > 1000000 and order by balance descending.

[Assistant]
SELECT sc.coin_type, sm.symbol, sm.name, sc.balance, sm.description
FROM sui_coins sc
JOIN sui_coins_metadata sm ON sc.coin_type = sm.coin_type
WHERE sm.status = 'exists'
  AND CAST(sc.balance AS numeric) > 1000000
ORDER BY CAST(sc.balance AS numeric) DESC;

[User] Also include the number of distinct owners per coin_type.

[Assistant]
SELECT sc.coin_type, sm.symbol, sm.name, sm.description,
       SUM(CAST(sc.balance AS numeric)) AS total_balance,
       COUNT(DISTINCT sc.owner) AS owner_count
FROM sui_coins sc
JOIN sui_coins_metadata sm ON sc.coin_type = sm.coin_type
WHERE sm.status = 'exists'
  AND CAST(sc.balance AS numeric) > 1000000
GROUP BY sc.coin_type, sm.symbol, sm.name, sm.description
ORDER BY total_balance DESC;

[User] Only show the top 3 coins by total_balance.

[Assistant]
SELECT sc.coin_type, sm.symbol, sm.name, sm.description,
       SUM(CAST(sc.balance AS numeric)) AS total_balance,
       COUNT(DISTINCT sc.owner) AS owner_count
FROM sui_coins sc
JOIN sui_coins_metadata sm ON sc.coin_type = sm.coin_type
WHERE sm.status = 'exists'
  AND CAST(sc.balance AS numeric) > 1000000
GROUP BY sc.coin_type, sm.symbol, sm.name, sm.description
ORDER BY total_balance 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 erc1155_approval_for_all (
    block_number bigint NOT NULL, -- Block number containing the transaction
    block_timestamp timestamp(3) NOT NULL, -- Timestamp of the block containing the transaction
    transaction_index integer NOT NULL, -- Index of the transaction within the block
    transaction_hash varchar(66) NOT NULL, -- Transaction hash
    log_index integer NOT NULL, -- Log index
    contract_address varchar(42) NOT NULL  -- Event contract address
)
CREATE TABLE erc20_balances ( block_number bigint, contract_address varchar, wallet_address varchar, amount varchar, pk varchar )
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 sui_coins ( object_id varchar NOT NULL, status varchar NOT NULL, coin_type varchar NOT NULL, balance varchar NOT NULL, owner varchar NOT NULL )
CREATE TABLE sui_coins_metadata (
    object_id varchar NOT NULL, -- object id of the coin metadata object
    coin_type varchar NOT NULL, -- coin type, eg. 0x...66::reap_token::REAP_TOKEN
    status varchar NOT NULL, -- coin status, eg. exists, deleted
    decimals bigint NOT NULL, -- decimals of the coin
    description varchar NOT NULL, -- description of the coin
    icon_url varchar NOT NULL, -- icon url of the coin
    symbol varchar NOT NULL, -- symbol of the coin
    name varchar NOT NULL  -- name of the coin
)
CREATE TABLE token_prices_latest ( blockchain.text, address.text, decimals.bigint, symbol.text, price.real, timestamp.timestamp )
CREATE TABLE erc20_approval ( block_number.bigint, block_timestamp.timestamp, transaction_index.integer, transaction_hash.text, log_index.integer, contract_address.text, pk.integer )
CREATE TABLE token_activities ( block_timestamp.timestamp, block_number.bigint, tx_index.integer, tx_hash.text, log_index.integer, type.text, tick.text, id.text, amt.decimal, from_address.text, to_address.text )
CREATE TABLE token_balances_bitcoin (
    block_number bigint NOT NULL, -- Block number containing the transaction
    block_timestamp timestamp(3) NOT NULL, -- Block timestamp containing the transaction
    tick varchar(255) NOT NULL, -- Ticker: Identifier of the inscription
    wallet_address varchar(42) NOT NULL, -- Address of owner
    total_supply varchar NOT NULL, -- Max supply: Set max supply of the inscription
    amount varchar 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 me the top 5 projects by valuation that completed fundraising rounds in the last 3 months, along with their narrative information if available.

[Assistant] SELECT pfr.project_name, pfr.valuation, pfr.rounds_name, pfr.investment_date, ni.narrative, ni.trend_rank FROM project_fundraising_record pfr LEFT JOIN token_basic_info tbi ON pfr.project_name = tbi.token_name LEFT JOIN narrative_info ni ON tbi.narrative = ni.narrative WHERE pfr.investment_date >= DATE_SUB(CURRENT_DATE, INTERVAL 3 MONTH) ORDER BY pfr.valuation DESC LIMIT 5;

[User] Can you also include the 24-hour trading volume for these projects' narratives and filter to only include projects with valuation over $50 million?

[Assistant] SELECT pfr.project_name, pfr.valuation, pfr.rounds_name, pfr.investment_date, ni.narrative, ni.trend_rank, ni.volume_24h FROM project_fundraising_record pfr LEFT JOIN token_basic_info tbi ON pfr.project_name = tbi.token_name LEFT JOIN narrative_info ni ON tbi.narrative = ni.narrative WHERE pfr.investment_date >= DATE_SUB(CURRENT_DATE, INTERVAL 3 MONTH) AND pfr.valuation > 50000000 ORDER BY pfr.valuation 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 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 token_basic_info ( coin_id character varying(100) NOT NULL, token_name character varying(100) NOT NULL, token_symbol character varying(100) NOT NULL, token_address character varying(100) NOT NULL, chain text, price double precision, price_change_percentage_1h double precision, price_change_percentage_24h double precision, price_change_percentage_7d double precision, highest_price_24h double precision, lowest_price_24h double precision, market_cap double precision, market_cap_rank bigint, market_cap_change_percentage_24h text, total_volume text, narrative text, trend_rank bigint )
 "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 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) )


[User] List the citizen IDs for individuals who have both uploaded documents and made payments.

[Assistant] SELECT DISTINCT T1.citizen_id FROM documents AS T1 JOIN payments AS T2 ON T1.citizen_id = T2.citizen_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 government_services.documents ( document_id character varying(64) NOT NULL, application_id character varying(64), citizen_id character varying(64) NOT NULL, document_type character varying(100) NOT NULL, file_reference text NOT NULL, upload_timestamp timestamp NOT NULL, expiry_date date, verification_status character varying(30) DEFAULT 'Pending', verified_by_employee_id character varying(64), verification_timestamp timestamp, PRIMARY KEY (document_id) )
CREATE TABLE government_services.payments ( payment_id character varying(64) NOT NULL, application_id character varying(64), citizen_id character varying(64) NOT NULL, service_id character varying(64), amount numeric(12, 2) NOT NULL, currency character varying(3) NOT NULL DEFAULT 'USD', payment_method character varying(50), payment_provider_reference character varying(128), payment_timestamp timestamp NOT NULL, status character varying(30) NOT NULL, notes text, PRIMARY KEY (payment_id) )


[User] Give me the total billed amount for each invoice in 2024.

[Assistant] SELECT invoice_id, SUM(hours_spent * billing_rate) AS total_billed_amount FROM legal_services.time_entries WHERE is_billed = TRUE AND EXTRACT(YEAR FROM date_worked) = 2024 GROUP BY invoice_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 legal_services.time_entries ( entry_id text PRIMARY KEY, case_id text, lawyer_id text, date_worked date, hours_spent numeric, billing_rate numeric, description text, is_billable bool, is_billed bool, invoice_id text, created_at timestamp )


[User] Show all rooms that are on floor 3.

[Assistant] SELECT room_id, property_id, room_number FROM hospitality_technology.rooms WHERE floor = 3;

[User] For these rooms, include the property name and room number.

[Assistant] SELECT r.room_number, p.property_name FROM hospitality_technology.rooms AS r JOIN hospitality_technology.properties AS p ON r.property_id = p.property_id WHERE r.floor = 3;

[User] Also, include the type name and current status for each room.

[Assistant] SELECT r.room_number, p.property_name, rt.type_name, r.status FROM hospitality_technology.rooms AS r JOIN hospitality_technology.properties AS p ON r.property_id = p.property_id JOIN hospitality_technology.room_types AS rt ON r.room_type_id = rt.room_type_id AND r.property_id = rt.property_id WHERE r.floor = 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 hospitality_technology.properties ( property_id text, property_name text, address_line1 text, address_line2 text, city text, state_province text, postal_code text, country_code text, phone_number text, email_address text, property_type text, star_rating numeric, timezone text, manager_staff_id text, created_at timestamp, updated_at timestamp )
CREATE TABLE hospitality_technology.rooms ( room_id text, property_id text, room_number text, room_type_id text, floor integer, status text, is_smoking boolean, features text, current_condition text, last_cleaned_at timestamp )
CREATE TABLE hospitality_technology.room_types ( room_type_id text, property_id text, type_name text, description text, base_rate numeric, max_occupancy integer, bed_type text, area_sqft numeric, amenities text )


[User] Find the average percentage share among all beneficiaries for each distinct relationship type.

[Assistant] SELECT relationship, AVG(percentage_share) FROM insurance.policy_beneficiaries GROUP BY relationship ORDER BY relationship;

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.insurance_products ( product_id.text, product_name.text, product_type.text, description.text, base_premium.numeric, coverage_details.text, underwriting_rules.text, is_active.boolean, created_at.timestamp, updated_at.timestamp )
CREATE TABLE insurance.policy_beneficiaries ( beneficiary_id text PRIMARY KEY, policy_id text, customer_id text, first_name text, last_name text, relationship text, percentage_share numeric, contact_info text, added_at timestamp )


[User] List all customers who reside in New York and were created in the system before 2023.

[Assistant] SELECT customer_id, first_name, last_name, created_at FROM insurance.customers WHERE state = 'NY' AND created_at < '2023-01-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 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 )


[User] For each event, display its event_id, the event_id of the previous event in the same transaction (if any), and the log_index of both events.

[Assistant]
SELECT curr.event_id   AS current_event_id,
       prev.event_id   AS previous_event_id,
       curr.log_index  AS current_log_index,
       prev.log_index  AS previous_log_index,
       curr.transaction_id
FROM web3.events curr
LEFT JOIN web3.events prev
  ON curr.transaction_id = prev.transaction_id
 AND curr.log_index = prev.log_index + 1;

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 web3.events ( event_id character varying(64) NOT NULL, contract_id character varying(64) NOT NULL, event_name character varying(128) NOT NULL, data text NOT NULL, emitted_at timestamp NOT NULL, transaction_id character varying(64) NOT NULL, log_index integer NOT NULL, PRIMARY KEY (event_id) )


[User] Show me all home loans (loan_id, principal_amount, interest_rate) where the current principal balance is more than 75% of the original principal amount, along with the account_id and employee details (first_name, last_name) of the employee who processed the loan application.

[Assistant] SELECT l.loan_id, l.principal_amount, l.interest_rate, l.account_id, e.first_name, e.last_name FROM financial_services.loans l JOIN financial_services.employees e ON l.account_id = e.employee_id WHERE l.loan_type = 'Home' AND l.current_principal_balance > (l.principal_amount * 0.75)

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.transactions ( transaction_id.text, account_id.text, related_account_id.text, transaction_type.text, amount.numeric, currency.text, transaction_date.timestamp, effective_date.date, description.text, status.text, reference_number.text )
CREATE TABLE financial_services.securities ( security_id.text, ticker_symbol.text, isin_code.text, cusip_code.text, security_name.text, security_type.text, exchange.text, currency.text, issuer_name.text, sector.text, last_updated.timestamp )
CREATE TABLE financial_services.market_data ( data_point_id.bigint, security_id.text, data_timestamp.timestamp, open_price.numeric, high_price.numeric, low_price.numeric, close_price.numeric, adjusted_close_price.numeric, volume.bigint, source.text )
CREATE TABLE financial_services.employees ( employee_id.text, first_name.text, last_name.text, job_title.text, department.text, branch_id.text, email.text, phone_extension.text, hire_date.date, termination_date.date, manager_id.text, status.text )
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] I need to find passengers who have a specific phone number prefix '+1555'. Can you help with that?

[Assistant] db.passengers.find({ phone_number: { $regex: '^\+1555' } }, { first_name: 1, last_name: 1, phone_number: 1, email: 1, _id: 0 })

[User] Can you also filter these results to include only passengers born before 1995?

[Assistant] db.passengers.find({ phone_number: { $regex: '^\+1555' }, date_of_birth: { $lt: ISODate('1995-01-01T00:00:00Z') } }, { first_name: 1, last_name: 1, phone_number: 1, email: 1, _id: 0 })

[User] Can you limit the results to the first 5 passengers?

[Assistant] db.passengers.find({ phone_number: { $regex: '^\+1555' }, date_of_birth: { $lt: ISODate('1995-01-01T00:00:00Z') } }, { first_name: 1, last_name: 1, phone_number: 1, email: 1, _id: 0 }).limit(5)

System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
// db.createCollection('passengers')
// Optional: db.passengers.createIndex({ passenger_id: 1 }, { unique: true })
// Optional: db.passengers.createIndex({ email: 1 }, { unique: true, sparse: true })
// Optional: db.passengers.createIndex({ phone_number: 1 }, { unique: true, sparse: true })
{
  _id: ObjectId(),
  passenger_id: "pass_pqr", // String (unique)
  first_name: "Alice", // String
  last_name: "Smith", // String
  email: "alice.smith@example.com", // String (unique, sparse)
  phone_number: "+15551234567", // String (unique, sparse)
  date_of_birth: ISODate("1990-03-20"), // Date
  loyalty_program_id: "LOYALTY123", // String
  created_at: ISODate("2023-02-01T11:00:00Z") // Date
}


[User] Show the usernames and registration dates for all users whose email ends with '@gmail.com'.

[Assistant] SELECT username, created_at FROM web3.users WHERE email LIKE '%@gmail.com';

[User] Actually, can you also include how many such users there are in total in the result?

[Assistant] SELECT username, created_at, COUNT(*) OVER() AS total_gmail_users FROM web3.users WHERE email LIKE '%@gmail.com';

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 web3.users ( user_id text, username text, email text, password_hash text, created_at timestamp )


[User] List the first and last names of employees and the full name of the citizens for whom they have scheduled appointments.

[Assistant] SELECT T1.first_name ,  T1.last_name ,  T3.first_name ,  T3.last_name FROM government_services.employees AS T1 JOIN government_services.appointments AS T2 ON T1.employee_id  =  T2.employee_id JOIN government_services.citizens AS T3 ON T2.citizen_id  =  T3.citizen_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 government_services.citizens ( citizen_id text PRIMARY KEY, national_id_number text, first_name text, last_name text, date_of_birth date, gender text, primary_address text, contact_email text, contact_phone text, registration_date timestamp, is_verified boolean )
CREATE TABLE government_services.agencies ( agency_id text PRIMARY KEY, agency_name text, jurisdiction_level text, primary_contact_email text, main_phone_number text, website_url text, established_date date, parent_agency_id text )
CREATE TABLE government_services.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 text PRIMARY KEY, citizen_id text, service_id text, submitted_at timestamp, status text, last_updated_at timestamp, assigned_employee_id text, decision_date date, notes text, reference_number text )
CREATE TABLE government_services.documents ( document_id text PRIMARY KEY, application_id text, citizen_id text, document_type text, file_reference text, upload_timestamp timestamp, expiry_date date, verification_status text, verified_by_employee_id text, verification_timestamp timestamp )
CREATE TABLE government_services.payments ( payment_id text PRIMARY KEY, application_id text, citizen_id text, service_id text, amount numeric, currency text, payment_method text, payment_provider_reference text, payment_timestamp timestamp, status text, notes text )
CREATE TABLE government_services.employees ( employee_id text PRIMARY KEY, agency_id text, first_name text, last_name text, job_title text, department text, work_email text, work_phone text, hire_date date, termination_date date, access_level text, manager_employee_id text )
CREATE TABLE government_services.appointments ( appointment_id text PRIMARY KEY, citizen_id text, employee_id text, location_id text, service_id text, scheduled_start_time timestamp, scheduled_end_time timestamp, purpose text, status text, booking_method text, created_at timestamp, notes text )
CREATE TABLE government_services.notifications ( notification_id text PRIMARY KEY, citizen_id text, application_id text, message_subject text, message_body text, channel text, sent_at timestamp, status text, related_entity_type text, related_entity_id text )


[User] For each KYC-approved user, list their wallet address and the date it was created.

[Assistant]
SELECT w.address, w.created_at
FROM trading_platform.wallets w
JOIN trading_platform.kyc_audit k ON w.user_id = k.user_id
WHERE k.status = 'approved';

[User] Could you also add the user's KYC reviewed_at date to the result?

[Assistant]
SELECT w.address, w.created_at, k.reviewed_at
FROM trading_platform.wallets w
JOIN trading_platform.kyc_audit k ON w.user_id = k.user_id
WHERE k.status = 'approved';

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.wallets ( wallet_id.text, user_id.text, address.text, private_key.text, created_at.timestamp )
CREATE TABLE trading_platform.dapps ( dapp_id.text, name.text, description.text, url.text )
CREATE TABLE trading_platform.kyc_audit ( kyc_audit_id.text, user_id.text, status.text, reviewed_at.timestamp )
CREATE TABLE trading_platform.logs ( log_id.text, user_id.text, action.text, details.text, logged_at.timestamp )


[User] Show me the number of direct replies each top-level comment has on post 'P200'.

[Assistant] SELECT c.comment_id, COUNT(r.comment_id) AS reply_count FROM comments AS c LEFT JOIN comments AS r ON r.parent_comment_id = c.comment_id WHERE c.post_id = 'P200' AND c.parent_comment_id IS NULL GROUP BY c.comment_id;

[User] Order by reply_count descending and limit to top 5.

[Assistant] SELECT c.comment_id, COUNT(r.comment_id) AS reply_count FROM comments AS c LEFT JOIN comments AS r ON r.parent_comment_id = c.comment_id WHERE c.post_id = 'P200' AND c.parent_comment_id IS NULL GROUP BY c.comment_id ORDER BY reply_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 social_media.comments ( comment_id.text, post_id.text, user_id.text, parent_comment_id.text, content.text, created_at.timestamp, updated_at.timestamp )


[User] Can you show, for each employee, the full name and job title of their direct manager, as well as the employee's department and branch_id?

[Assistant]
SELECT e.employee_id, e.first_name AS employee_first_name, e.last_name AS employee_last_name, e.department AS employee_department, e.branch_id AS employee_branch_id, m.first_name AS manager_first_name, m.last_name AS manager_last_name, m.job_title AS manager_job_title
FROM financial_services.employees e
LEFT JOIN financial_services.employees m ON e.manager_id = m.employee_id;

[User] Actually, show only employees who have a manager assigned, and include only those where the manager works at a different branch than the employee.

[Assistant]
SELECT e.employee_id, e.first_name AS employee_first_name, e.last_name AS employee_last_name, e.department AS employee_department, e.branch_id AS employee_branch_id, m.first_name AS manager_first_name, m.last_name AS manager_last_name, m.job_title AS manager_job_title, m.branch_id AS manager_branch_id
FROM financial_services.employees e
INNER JOIN financial_services.employees m ON e.manager_id = m.employee_id
WHERE e.branch_id IS DISTINCT FROM m.branch_id;

[User] Now, only include employees who were hired after 2021-01-01.

[Assistant]
SELECT e.employee_id, e.first_name AS employee_first_name, e.last_name AS employee_last_name, e.department AS employee_department, e.branch_id AS employee_branch_id, m.first_name AS manager_first_name, m.last_name AS manager_last_name, m.job_title AS manager_job_title, m.branch_id AS manager_branch_id
FROM financial_services.employees e
INNER JOIN financial_services.employees m ON e.manager_id = m.employee_id
WHERE e.branch_id IS DISTINCT FROM m.branch_id
  AND e.hire_date > '2021-01-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 financial_services.accounts ( account_id text, customer_id text, account_number text, account_type text, balance numeric, currency text, opened_date date, status text, interest_rate numeric, last_updated_at timestamp )
CREATE TABLE financial_services.transactions (
    transaction_id character varying(64) NOT NULL, -- unique identifier for the transaction
    account_id character varying(64) NOT NULL, -- account involved in the transaction
    related_account_id character varying(64), -- counterpart account for transfers
    transaction_type character varying(50) NOT NULL, -- e.g., Deposit, Withdrawal, Transfer, Payment, Fee, Interest
    amount numeric(19, 4) NOT NULL, -- transaction amount
    currency character varying(3) NOT NULL, -- transaction currency
    transaction_date timestamp NOT NULL, -- exact time of the transaction
    effective_date date NOT NULL, -- date the transaction affects the balance
    description text, -- description or memo of the transaction
    status character varying(32) NOT NULL, -- e.g., Pending, Completed, Failed, Reversed
    reference_number character varying(128), -- external reference if applicable (e.g., check number)
    PRIMARY KEY (transaction_id),
    FOREIGN KEY (account_id) REFERENCES financial_services.accounts(account_id),
    FOREIGN KEY (related_account_id) REFERENCES financial_services.accounts(account_id)
)
CREATE TABLE financial_services.trades ( trade_id text PRIMARY KEY, account_id text, security_id text, order_id text, trade_type text, quantity numeric, price_per_unit numeric, total_amount numeric, commission numeric, trade_timestamp timestamp, settlement_date date, status text, execution_venue text )
CREATE TABLE financial_services.market_data ( data_point_id.bigint, security_id.text, data_timestamp.timestamp, open_price.numeric, high_price.numeric, low_price.numeric, close_price.numeric, adjusted_close_price.numeric, volume.bigint, source.text )
CREATE TABLE financial_services.employees (
    employee_id character varying(64) NOT NULL,  -- unique identifier for the employee
    first_name character varying(100) NOT NULL,
    last_name character varying(100) NOT NULL,
    job_title character varying(100) NOT NULL, -- e.g., Teller, Branch Manager, Financial Advisor, Analyst
    department character varying(100), -- e.g., Retail Banking, Wealth Management, IT
    branch_id character varying(64), -- Identifier for the branch they work at (if applicable)
    email character varying(128) NOT NULL UNIQUE,
    phone_extension character varying(20),
    hire_date date NOT NULL,
    termination_date date, -- Date of termination, null if currently employed
    manager_id character varying(64), -- Self-referencing key for manager relationship
    status character varying(32) NOT NULL, -- e.g., Active, Terminated, On Leave
    PRIMARY KEY (employee_id),
    FOREIGN KEY (branch_id) REFERENCES financial_services.branches(branch_id), -- Assuming a branches table exists
    FOREIGN KEY (manager_id) REFERENCES financial_services.employees(employee_id)
)
CREATE TABLE financial_services.loans ( loan_id character varying(64) NOT NULL, account_id character varying(64) NOT NULL UNIQUE, loan_type character varying(50) NOT NULL, principal_amount numeric(19, 4) NOT NULL, current_principal_balance numeric(19, 4) NOT NULL, interest_rate numeric(6, 4) NOT NULL, term_months integer NOT NULL, origination_date date NOT NULL, maturity_date date NOT NULL, monthly_payment numeric(12, 4), collateral_description text, status character varying(32) NOT NULL, PRIMARY KEY (loan_id), FOREIGN KEY (account_id) REFERENCES financial_services.accounts(account_id) )


[User] Can you provide the total number of cars associated with a specific train with train_id 'train_789'?

[Assistant] SCARD train:train_789:cars

System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
// Use Hashes for platform details. Key format: platform:<platform_id>
// HSET platform:plat_123 platform_id "plat_123" station_id "station_xyz" platform_number "1A" track_number "T1" status "Operational" length_meters 250.50 accessible 1

// To link platforms to stations (optional):
// SADD station:station_xyz:platforms platform:plat_123 platform:plat_456
// Use Hashes for train details. Key format: train:<train_id>
// HSET train:train_789 train_id "train_789" train_number "Acela 2151" model "Siemens Velaro" ... status "Active" ...

// To find train by train_number (optional index):
// SET train_number:"Acela 2151" train:train_789
// Use Hashes for car details. Key format: car:<car_id>
// HSET car:car_abc car_id "car_abc" train_id "train_789" car_number "C3" car_type "Passenger" class "Business" capacity 60 features "WiFi,Power Outlet"

// To link cars to trains (optional):
// SADD train:train_789:cars car:car_abc car:car_def
// Use Hashes for details. Key format: route_station:<route_station_id>
// HSET route_station:rs_ne_1 route_station_id "rs_ne_1" route_id "route_ne_corr" station_id "station_bos" sequence_order 1 ...

// To find stops for a route, use a Sorted Set (score by sequence_order):
// ZADD route:route_ne_corr:stops 1 route_station:rs_ne_1
// ZADD route:route_ne_corr:stops 2 route_station:rs_ne_2
// Use Hashes for schedule details. Key format: schedule:<schedule_id>
// HSET schedule:sched_1122 schedule_id "sched_1122" train_id "train_789" route_id "route_ne_corr" departure_datetime "2024-05-10T08:00:00-04:00" ... status "Scheduled"
// Use Hashes for details. Key format: schedule_stop:<stop_id>
// HSET schedule_stop:stop_sched1122_1 stop_id "stop_sched1122_1" schedule_id "sched_1122" station_id "station_bos" ...

// To find stops for a schedule, use a Sorted Set (score by sequence_order):
// ZADD schedule:sched_1122:stops 1 schedule_stop:stop_sched1122_1
// ZADD schedule:sched_1122:stops 2 schedule_stop:stop_sched1122_2
// Use Hashes for passenger details. Key format: passenger:<passenger_id>
// HSET passenger:pass_pqr passenger_id "pass_pqr" first_name "Alice" last_name "Smith" email "alice.smith@example.com" ...

// To find passenger by email (optional index):
// SET passenger_email:"alice.smith@example.com" passenger:pass_pqr
// Use Hashes for booking details. Key format: booking:<booking_id>
// HSET booking:book_zyx booking_id "book_zyx" passenger_id "pass_pqr" schedule_id "sched_1122" ... status "Confirmed" ...

// To link bookings to passengers/schedules (optional):
// SADD passenger:pass_pqr:bookings booking:book_zyx
// SADD schedule:sched_1122:bookings booking:book_zyx
// Use Hashes for ticket details. Key format: ticket:<ticket_id>
// HSET ticket:tkt_1a2b ticket_id "tkt_1a2b" booking_id "book_zyx" car_id "car_abc" seat_number "12A" ... is_checked_in 0 ...

// To link tickets to bookings (optional):
// SADD booking:book_zyx:tickets ticket:tkt_1a2b
// Use Hashes for staff details. Key format: staff:<staff_id>
// HSET staff:staff_mno staff_id "staff_mno" first_name "Bob" ... employee_number "E12345" ... is_active 1

// To find staff by employee number (optional index):
// SET staff_employee_number:"E12345" staff:staff_mno
// Use Hashes for maintenance record details. Key format: maintenance_record:<record_id>
// HSET maintenance_record:maint_rec_001 record_id "maint_rec_001" asset_id "train_789" asset_type "Train" ... status "Completed"

// To link records to assets (optional):
// SADD train:train_789:maintenance maintenance_record:maint_rec_001
// SADD platform:plat_123:maintenance maintenance_record:maint_rec_002


[User] How many documents are there for each document_type? Show document_type and count ordered by the count in descending order.

[Assistant]
SELECT document_type,
       COUNT(*) AS count
FROM legal_services.documents
GROUP BY document_type
ORDER BY 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 legal_services.documents ( document_id.text, case_id.text, document_name.text, document_type.text, storage_path.text, uploaded_by_lawyer_id.text, upload_timestamp.timestamp, version.integer, description.text )


[User] Count the number of prescriptions each doctor has written for medications manufactured by 'Pfizer' in the last 6 months.

[Assistant]
SELECT p.doctor_id, COUNT(*) AS prescription_count
FROM healthcare.prescriptions p
JOIN healthcare.medications m ON p.medication_id = m.medication_id
WHERE m.manufacturer = 'Pfizer'
  AND p.prescription_date >= CURRENT_DATE - INTERVAL '6 months'
GROUP BY p.doctor_id;

[User] Actually, please include the doctor's full name instead of the ID, and order the results by prescription_count descending.

[Assistant]
SELECT p.doctor_id,
       d.first_name || ' ' || d.last_name AS doctor_name,
       COUNT(*) AS prescription_count
FROM healthcare.prescriptions p
JOIN healthcare.medications m ON p.medication_id = m.medication_id
JOIN healthcare.doctors d ON p.doctor_id = d.doctor_id
WHERE m.manufacturer = 'Pfizer'
  AND p.prescription_date >= CURRENT_DATE - INTERVAL '6 months'
GROUP BY p.doctor_id, doctor_name
ORDER BY prescription_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 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.appointments ( appointment_id.text, patient_id.text, doctor_id.text, appointment_time.timestamp, duration_minutes.integer, reason.text, status.text, location_id.text, notes.text, created_at.timestamp )
CREATE TABLE healthcare.medications (
    medication_id character varying(64) NOT NULL, -- unique identifier for the medication type
    medication_name character varying(255) NOT NULL, -- common or brand name
    generic_name character varying(255), -- generic chemical name
    manufacturer character varying(100), -- drug manufacturer
    ndc_code character varying(20) UNIQUE, -- National Drug Code (optional but useful)
    description text, -- description of the medication
    PRIMARY KEY (medication_id)
)
CREATE TABLE healthcare.prescriptions ( prescription_id text, record_id text, patient_id text, doctor_id text, medication_id text, dosage text, frequency text, route text, start_date date, end_date date, quantity_dispensed numeric, refills_allowed integer, prescription_date timestamp )
CREATE TABLE healthcare.insurance_plans ( plan_id text, plan_name text, insurance_provider text, plan_type text, contact_phone text, website text )
CREATE TABLE healthcare.patient_insurance ( patient_insurance_id text, patient_id text, plan_id text, policy_number text, group_number text, subscriber_name text, effective_date date, expiration_date date, is_primary boolean )


[User] List all depots (location type 'Depot') and the number of vehicles assigned to each. Include the depot name and city.

[Assistant] SELECT T1.name ,  T1.city ,  COUNT(T2.vehicle_id) FROM transportation.locations AS T1 LEFT JOIN transportation.vehicles AS T2 ON T1.location_id  =  T2.depot_id WHERE T1.type  =  'Depot' GROUP BY T1.location_id ,  T1.name ,  T1.city

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,  -- unique identifier for the vehicle
    license_plate character varying(32) NOT NULL UNIQUE, -- vehicle license plate
    vin character varying(17) UNIQUE, -- vehicle identification number
    make character varying(64) NOT NULL, -- manufacturer of the vehicle
    model character varying(64) NOT NULL, -- model of the vehicle
    year integer NOT NULL, -- manufacturing year
    type character varying(32) NOT NULL, -- type of vehicle (e.g., Bus, Train, Truck, Car, Van)
    capacity integer, -- passenger or cargo capacity
    fuel_type character varying(32) NOT NULL, -- e.g., Diesel, Gasoline, Electric, Hydrogen
    status character varying(32) NOT NULL, -- e.g., Active, Maintenance, Decommissioned
    depot_id character varying(64), -- identifier of the home depot/base
    acquisition_date date, -- date the vehicle was acquired
    PRIMARY KEY (vehicle_id)
)
CREATE TABLE transportation.drivers (
    driver_id character varying(64) NOT NULL,  -- unique identifier for the driver
    employee_id character varying(64) NOT NULL UNIQUE, -- employee reference number
    first_name character varying(128) NOT NULL, -- driver's first name
    last_name character varying(128) NOT NULL, -- driver's last name
    license_number character varying(64) NOT NULL UNIQUE, -- driving license number
    license_expiry_date date NOT NULL, -- expiry date of the license
    contact_number character varying(32), -- phone number
    email character varying(128) UNIQUE, -- email address
    hire_date date NOT NULL, -- date the driver was hired
    status character varying(32) NOT NULL, -- e.g., Active, On Leave, Terminated
    PRIMARY KEY (driver_id)
)
CREATE TABLE transportation.routes (
    route_id character varying(64) NOT NULL,  -- unique identifier for the route
    route_number character varying(32) NOT NULL UNIQUE, -- public-facing route number/name
    description text, -- description of the route
    origin_location_id character varying(64) NOT NULL, -- identifier of the starting location
    destination_location_id character varying(64) NOT NULL, -- identifier of the ending location
    distance_km numeric(10, 2), -- estimated distance in kilometers
    estimated_duration_minutes integer, -- estimated travel time in minutes
    type character varying(32) NOT NULL, -- e.g., City Bus, Intercity Train, Cargo Delivery
    PRIMARY KEY (route_id)
)
CREATE TABLE transportation.locations (
    location_id character varying(64) NOT NULL,  -- unique identifier for the location
    name character varying(255) NOT NULL, -- name of the location (e.g., Central Station, Depot Alpha, Pier 7)
    type character varying(64) NOT NULL, -- e.g., Station, Stop, Depot, Port, Airport, Customer Address
    address_line1 character varying(255), -- street address
    city character varying(128), -- city name
    state_province character varying(128), -- state or province
    postal_code character varying(32), -- postal code
    country character varying(64) NOT NULL, -- country name
    latitude numeric(9, 6), -- geographic latitude
    longitude numeric(9, 6), -- geographic longitude
    timezone character varying(64), -- IANA timezone name (e.g., America/New_York)
    PRIMARY KEY (location_id)
)
CREATE TABLE transportation.fuel_logs (
    fuel_log_id character varying(64) NOT NULL,  -- unique identifier for the fuel log entry
    vehicle_id character varying(64) NOT NULL, -- identifier of the vehicle fueled
    trip_id character varying(64), -- optional: identifier of the trip during which fueling occurred
    log_timestamp timestamp with time zone NOT NULL, -- time when fueling occurred
    fuel_type character varying(32) NOT NULL, -- type of fuel added (matches vehicle's fuel type)
    quantity numeric(10, 3) NOT NULL, -- amount of fuel added (e.g., Liters, Gallons, kWh)
    unit character varying(16) NOT NULL, -- unit of quantity (e.g., L, gal, kWh)
    cost_per_unit numeric(8, 4), -- price per unit of fuel
    total_cost numeric(10, 2) NOT NULL, -- total cost of the fuel purchase
    odometer_reading integer, -- vehicle mileage at time of fueling
    location_id character varying(64), -- identifier of the fueling station/location
    PRIMARY KEY (fuel_log_id)
)


[User] Show the number of active agents in each license state.

[Assistant]
SELECT license_state,
       COUNT(*) AS active_agent_count
FROM insurance.agents
WHERE status = 'active'
GROUP BY license_state;

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 PRIMARY KEY, 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] Which customers have policies that expired in the last month? Please show the customer ID, policy number, and expiration date.

[Assistant]
SELECT c.customer_id, p.policy_number, p.end_date
FROM insurance.customers c
JOIN insurance.policies p ON c.customer_id = p.customer_id
WHERE p.end_date >= (CURRENT_DATE - INTERVAL '1 month') AND p.end_date < CURRENT_DATE;

[User] Add the customer's email to the results.

[Assistant]
SELECT c.customer_id, c.email, p.policy_number, p.end_date
FROM insurance.customers c
JOIN insurance.policies p ON c.customer_id = p.customer_id
WHERE p.end_date >= (CURRENT_DATE - INTERVAL '1 month') AND p.end_date < CURRENT_DATE;

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.policies ( policy_id text, customer_id text, product_id text, agent_id text, policy_number text, start_date date, end_date date, premium_amount numeric, coverage_limit numeric, deductible numeric, status text, issued_at timestamp, cancellation_date date, cancellation_reason text )
CREATE TABLE insurance.claims ( claim_id text, policy_id text, customer_id text, incident_date timestamp, reported_date timestamp, description text, estimated_loss numeric, status text, settlement_amount numeric, settlement_date date, claim_handler_id text, police_report_number text )
CREATE TABLE insurance.insurance_products ( product_id text, product_name text, product_type text, description text, base_premium numeric, coverage_details text, underwriting_rules text, is_active boolean, created_at timestamp, updated_at timestamp )


[User] List all pairs of wallets that were created within 10 minutes of each other, showing both wallet IDs, the user_id, and both creation timestamps.

[Assistant]
SELECT
  w1.wallet_id AS wallet1_id,
  w2.wallet_id AS wallet2_id,
  w1.user_id,
  w1.created_at AS created_at1,
  w2.created_at AS created_at2
FROM web3.wallets w1
JOIN web3.wallets w2
  ON w1.user_id = w2.user_id
  AND w1.wallet_id < w2.wallet_id
  AND ABS(EXTRACT(EPOCH FROM (w1.created_at - w2.created_at))) <= 600;

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 web3.wallets ( wallet_id text, user_id text, address text, private_key text, created_at timestamp )


[User] How many documents were uploaded in the year 2023?

[Assistant] SELECT count(*) FROM government_services.documents WHERE date_part('year', upload_timestamp) = 2023;

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.documents ( document_id character varying(64) NOT NULL, application_id character varying(64), citizen_id character varying(64) NOT NULL, document_type character varying(100) NOT NULL, file_reference text NOT NULL, upload_timestamp timestamp NOT NULL, expiry_date date, verification_status character varying(30) DEFAULT 'Pending', verified_by_employee_id character varying(64), verification_timestamp timestamp, PRIMARY KEY (document_id) )


[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] Find all contracts where the deployer address is the same as the contract address, indicating self-deployed contracts, and show their network IDs and deployment timestamps.

[Assistant] SELECT address, network_id, deployed_at FROM web3.contracts WHERE address = deployer_address;

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 web3.contracts ( contract_id character varying(64) NOT NULL, address character varying(128) NOT NULL, abi text NOT NULL, bytecode text NOT NULL, deployer_address character varying(128) NOT NULL, deployed_at timestamp NOT NULL, network_id character varying(64) NOT NULL, status character varying(32) NOT NULL, PRIMARY KEY (contract_id) )


[User] List all pairs of law firms that were founded on the same month and day, showing their names, and the shared founding date. Exclude firms founded on January 1st.

[Assistant] SELECT t1.firm_name AS firm1_name, t2.firm_name AS firm2_name, t1.founded_date FROM legal_services.law_firms AS t1 JOIN legal_services.law_firms AS t2 ON MONTH(t1.founded_date) = MONTH(t2.founded_date) AND DAY(t1.founded_date) = DAY(t2.founded_date) AND t1.firm_id < t2.firm_id WHERE MONTH(t1.founded_date) <> 1 OR DAY(t1.founded_date) <> 1;

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.law_firms ( firm_id character varying(64) NOT NULL, firm_name character varying(200) NOT NULL, address text NOT NULL, phone character varying(32), website character varying(255), founded_date date, managing_partner_id character varying(64), PRIMARY KEY (firm_id) )


[User] List all appointments scheduled in the next 30 days with appointment_id, client_id, case_id, and any invoice_id linked to that case.

[Assistant]
SELECT
  a.appointment_id,
  a.client_id,
  a.case_id,
  i.invoice_id
FROM legal_services.appointments AS a
LEFT JOIN legal_services.invoices AS i
  ON a.case_id = i.case_id
WHERE a.start_time BETWEEN CURRENT_DATE AND CURRENT_DATE + INTERVAL '30 days';

[User] Change to include only appointments with status 'Scheduled' and invoices that are not fully paid.

[Assistant]
SELECT
  a.appointment_id,
  a.client_id,
  a.case_id,
  i.invoice_id
FROM legal_services.appointments AS a
LEFT JOIN legal_services.invoices AS i
  ON a.case_id = i.case_id
WHERE a.start_time BETWEEN CURRENT_DATE AND CURRENT_DATE + INTERVAL '30 days'
  AND a.status = 'Scheduled'
  AND (i.status IS NULL OR i.status <> 'Paid');

[User] Also include only those where the case_type is 'Corporate'.

[Assistant]
SELECT
  a.appointment_id,
  a.client_id,
  a.case_id,
  i.invoice_id
FROM legal_services.appointments AS a
JOIN legal_services.cases AS c
  ON a.case_id = c.case_id
LEFT JOIN legal_services.invoices AS i
  ON a.case_id = i.case_id
WHERE a.start_time BETWEEN CURRENT_DATE AND CURRENT_DATE + INTERVAL '30 days'
  AND a.status = 'Scheduled'
  AND (i.status IS NULL OR i.status <> 'Paid')
  AND c.case_type = 'Corporate';

[User] Finally, order by start_time ascending and return only the first 10 rows.

[Assistant]
SELECT
  a.appointment_id,
  a.client_id,
  a.case_id,
  i.invoice_id
FROM legal_services.appointments AS a
JOIN legal_services.cases AS c
  ON a.case_id = c.case_id
LEFT JOIN legal_services.invoices AS i
  ON a.case_id = i.case_id
WHERE a.start_time BETWEEN CURRENT_DATE AND CURRENT_DATE + INTERVAL '30 days'
  AND a.status = 'Scheduled'
  AND (i.status IS NULL OR i.status <> 'Paid')
  AND c.case_type = 'Corporate'
ORDER BY a.start_time 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.law_firms (
    firm_id character varying(64) NOT NULL,  -- unique identifier for the law firm
    firm_name character varying(200) NOT NULL, -- official name of the law firm
    address text NOT NULL, -- primary address of the firm
    phone character varying(32), -- firm's main phone number
    website character varying(255), -- firm's website URL
    founded_date date, -- date the firm was established
    managing_partner_id character varying(64), -- FK to lawyers table (optional)
    PRIMARY KEY (firm_id)
)
CREATE TABLE legal_services.cases (
    case_id character varying(64) NOT NULL,  -- unique identifier for the case/matter
    case_number character varying(100) UNIQUE, -- official case number (court or internal)
    case_name text NOT NULL, -- descriptive name or title for the case
    client_id character varying(64) NOT NULL, -- FK to clients table
    lead_lawyer_id character varying(64) NOT NULL, -- FK to lawyers table (primary lawyer responsible)
    case_type character varying(100) NOT NULL, -- e.g., Litigation, Corporate, Family Law, IP
    status character varying(50) NOT NULL, -- e.g., Open, Closed, Pending, On Hold, Appealed
    date_opened timestamp NOT NULL, -- date the case was formally opened
    date_closed timestamp, -- date the case was closed (nullable)
    description text, -- detailed description of the case
    court_jurisdiction character varying(128), -- court or jurisdiction if applicable
    PRIMARY KEY (case_id)
)
CREATE TABLE legal_services.time_entries (
    entry_id character varying(64) NOT NULL,  -- unique identifier for the time entry
    case_id character varying(64) NOT NULL, -- FK to cases table
    lawyer_id character varying(64) NOT NULL, -- FK to lawyers table (who performed the work)
    date_worked date NOT NULL, -- date the work was performed
    hours_spent numeric(5, 2) NOT NULL CHECK (hours_spent > 0), -- duration of work in hours (e.g., 1.5 for 1h 30m)
    billing_rate numeric(10, 2) NOT NULL, -- hourly rate applied for this entry
    description text NOT NULL, -- detailed description of the work performed
    is_billable boolean DEFAULT true, -- whether this time entry is billable to the client
    is_billed boolean DEFAULT false, -- whether this entry has been included in an invoice
    invoice_id character varying(64), -- FK to invoices table (once billed)
    created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, -- when the entry was recorded
    PRIMARY KEY (entry_id)
)
CREATE TABLE legal_services.invoices (
    invoice_id character varying(64) NOT NULL,  -- unique identifier for the invoice
    invoice_number character varying(100) UNIQUE NOT NULL, -- user-facing invoice number
    client_id character varying(64) NOT NULL, -- FK to clients table
    case_id character varying(64), -- FK to cases table (optional, could be general retainer)
    issue_date date NOT NULL, -- date the invoice was generated
    due_date date NOT NULL, -- date the payment is due
    total_amount numeric(12, 2) NOT NULL, -- total amount due on the invoice
    amount_paid numeric(12, 2) DEFAULT 0.00, -- amount already paid
    status character varying(50) NOT NULL, -- e.g., Draft, Sent, Paid, Partially Paid, Overdue, Void
    payment_date timestamp, -- date the invoice was fully paid (nullable)
    notes text, -- additional notes or terms on the invoice
    created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
    PRIMARY KEY (invoice_id)
)
CREATE TABLE legal_services.appointments (
    appointment_id character varying(64) NOT NULL, -- unique identifier for the appointment
    client_id character varying(64) NOT NULL, -- FK to clients table
    lawyer_id character varying(64) NOT NULL, -- FK to lawyers table
    case_id character varying(64), -- FK to cases table (optional, if related to a specific case)
    start_time timestamp NOT NULL, -- scheduled start date and time
    end_time timestamp NOT NULL, -- scheduled end date and time
    location text, -- location of the meeting (address or virtual link)
    subject character varying(255), -- subject or purpose of the appointment
    notes text, -- additional notes for the appointment
    status character varying(50) NOT NULL, -- e.g., Scheduled, Completed, Canceled, Rescheduled
    created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
    PRIMARY KEY (appointment_id)
)


[User] For each vehicle, list its vehicle_id, license_plate, and any older vehicle of the same type (showing older_vehicle_id and older year).

[Assistant]
SELECT cur.vehicle_id,
       cur.license_plate,
       old.vehicle_id AS older_vehicle_id,
       old.year       AS older_vehicle_year
FROM transportation.vehicles cur
JOIN transportation.vehicles old
  ON cur.type = old.type
 AND old.year < cur.year
ORDER BY cur.vehicle_id, old.year 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,  -- unique identifier for the vehicle
    license_plate character varying(32) NOT NULL UNIQUE, -- vehicle license plate
    vin character varying(17) UNIQUE, -- vehicle identification number
    make character varying(64) NOT NULL, -- manufacturer of the vehicle
    model character varying(64) NOT NULL, -- model of the vehicle
    year integer NOT NULL, -- manufacturing year
    type character varying(32) NOT NULL, -- type of vehicle (e.g., Bus, Train, Truck, Car, Van)
    capacity integer, -- passenger or cargo capacity
    fuel_type character varying(32) NOT NULL, -- e.g., Diesel, Gasoline, Electric, Hydrogen
    status character varying(32) NOT NULL, -- e.g., Active, Maintenance, Decommissioned
    depot_id character varying(64), -- identifier of the home depot/base
    acquisition_date date, -- date the vehicle was acquired
    PRIMARY KEY (vehicle_id)
)


[User] Show me each user's username, their wallet address, and the total quantity of open orders they have placed, along with the name of the asset for each order.

[Assistant]
SELECT u.username, w.address, o.asset_id, SUM(o.quantity) AS total_open_quantity
FROM trading_platform.users u
JOIN trading_platform.wallets w ON u.user_id = w.user_id
JOIN trading_platform.orders o ON w.wallet_id = o.wallet_id
WHERE o.status = 'open'
GROUP BY u.username, w.address, o.asset_id
ORDER BY u.username, w.address, o.asset_id;

[User] Can you also include the email address for each user and only show those with at least 2 open orders?

[Assistant]
SELECT u.username, u.email, w.address, o.asset_id, SUM(o.quantity) AS total_open_quantity, COUNT(o.order_id) AS open_order_count
FROM trading_platform.users u
JOIN trading_platform.wallets w ON u.user_id = w.user_id
JOIN trading_platform.orders o ON w.wallet_id = o.wallet_id
WHERE o.status = 'open'
GROUP BY u.username, u.email, w.address, o.asset_id
HAVING COUNT(o.order_id) >= 2
ORDER BY u.username, w.address, o.asset_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 trading_platform.users (
    user_id character varying(64) NOT NULL,  -- unique identifier for the user
    username character varying(128) NOT NULL, -- username of the user
    email character varying(128) NOT NULL, -- email address of the user
    password_hash text NOT NULL, -- hashed password of the user
    created_at timestamp NOT NULL, -- time when the user account was created
    PRIMARY KEY (user_id)
)
CREATE TABLE trading_platform.wallets ( wallet_id.text, user_id.text, address.text, private_key.text, created_at.timestamp )
CREATE TABLE trading_platform.orders ( order_id.text, user_id.text, wallet_id.text, asset_id.text, order_type.text, quantity.numeric, price.numeric, status.text, created_at.timestamp )
CREATE TABLE trading_platform.utxos ( utxo_id text PRIMARY KEY, transaction_id text, output_index int, address text, amount numeric, spent boolean )
CREATE TABLE trading_platform.peers ( peer_id.text, ip_address.text, port.integer, last_seen.timestamp )
CREATE TABLE trading_platform.metadata ( metadata_id character varying(64) NOT NULL, asset_id character varying(64) NOT NULL, key character varying(128) NOT NULL, value text NOT NULL, PRIMARY KEY (metadata_id) )
CREATE TABLE trading_platform.kyc_audit (
    kyc_audit_id character varying(64) NOT NULL,  -- unique identifier for the KYC audit
    user_id character varying(64) NOT NULL, -- identifier of the user being audited
    status character varying(32) NOT NULL, -- status of the KYC audit (e.g., pending, approved, rejected)
    reviewed_at timestamp NOT NULL, -- time when the KYC audit was reviewed
    PRIMARY KEY (kyc_audit_id)
)
CREATE TABLE trading_platform.logs ( log_id character varying(64) NOT NULL, user_id character varying(64), action character varying(128) NOT NULL, details text NOT NULL, logged_at timestamp NOT NULL, PRIMARY KEY (log_id) )
CREATE TABLE trading_platform.notifications ( notification_id.text, user_id.text, message.text, sent_at.timestamp, read_at.timestamp )


[User] List all medical records created in the last 7 days, including patient_id, doctor_id, and record_date.

[Assistant] SELECT patient_id, doctor_id, record_date FROM healthcare.medical_records WHERE created_at >= CURRENT_DATE - INTERVAL '7 days';

[User] Actually, I only need records where the treatment_plan is not empty.

[Assistant] SELECT patient_id, doctor_id, record_date FROM healthcare.medical_records WHERE created_at >= CURRENT_DATE - INTERVAL '7 days' AND treatment_plan IS NOT NULL AND treatment_plan != '';

[User] Can you also sort them by record_date in descending order?

[Assistant] SELECT patient_id, doctor_id, record_date FROM healthcare.medical_records WHERE created_at >= CURRENT_DATE - INTERVAL '7 days' AND treatment_plan IS NOT NULL AND treatment_plan != '' ORDER BY record_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.medical_records ( record_id.text, patient_id.text, appointment_id.text, doctor_id.text, record_date.timestamp, chief_complaint.text, present_illness_history.text, past_medical_history.text, physical_examination_notes.text, assessment.text, treatment_plan.text, vitals.json, created_at.timestamp )


[User] Show me all customers (customer_id, first_name, last_name) who have made trades in the last 30 days, along with the total trade amount for each customer, sorted by total trade amount in descending order.

[Assistant] SELECT c.customer_id, c.first_name, c.last_name, SUM(t.total_amount) AS total_trade_amount FROM financial_services.customers c JOIN financial_services.accounts a ON c.customer_id = a.customer_id JOIN financial_services.trades t ON a.account_id = t.account_id WHERE t.trade_timestamp >= CURRENT_DATE - INTERVAL '30 days' GROUP BY c.customer_id, c.first_name, c.last_name ORDER BY total_trade_amount DESC;

[User] Now modify the query to only include trades executed on the 'NYSE' venue and include the trade count for each customer.

[Assistant] SELECT c.customer_id, c.first_name, c.last_name, SUM(t.total_amount) AS total_trade_amount, COUNT(t.trade_id) AS trade_count FROM financial_services.customers c JOIN financial_services.accounts a ON c.customer_id = a.customer_id JOIN financial_services.trades t ON a.account_id = t.account_id WHERE t.trade_timestamp >= CURRENT_DATE - INTERVAL '30 days' AND t.execution_venue = 'NYSE' GROUP BY c.customer_id, c.first_name, c.last_name ORDER BY total_trade_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.customers (
    customer_id character varying(64) NOT NULL,  -- unique identifier for the customer
    first_name character varying(100) NOT NULL, -- customer's first name
    last_name character varying(100) NOT NULL, -- customer's last name
    date_of_birth date NOT NULL, -- customer's date of birth
    ssn_hash character varying(128), -- hashed social security number (or national ID)
    address text NOT NULL, -- customer's primary address
    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,
    email character varying(128) UNIQUE, -- customer's email address
    phone_number character varying(32),
    created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, -- timestamp of customer record creation
    status character varying(32) NOT NULL, -- e.g., Active, Inactive, Pending Verification
    risk_profile character varying(50), -- e.g., Low, Medium, High
    PRIMARY KEY (customer_id)
)
CREATE TABLE financial_services.securities (
    security_id character varying(64) NOT NULL, -- unique identifier for the security
    ticker_symbol character varying(20) NOT NULL UNIQUE, -- stock ticker or fund symbol
    isin_code character varying(12) UNIQUE, -- International Securities Identification Number
    cusip_code character varying(9) UNIQUE, -- CUSIP number
    security_name text NOT NULL, -- full name of the security
    security_type character varying(50) NOT NULL, -- e.g., Stock, Bond, ETF, Mutual Fund, Option, Future
    exchange character varying(50), -- primary exchange where traded (e.g., NYSE, NASDAQ)
    currency character varying(3) NOT NULL, -- currency the security is denominated in
    issuer_name character varying(255), -- name of the issuing entity
    sector character varying(100), -- industry sector
    last_updated timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
    PRIMARY KEY (security_id)
)
CREATE TABLE financial_services.trades (
    trade_id character varying(64) NOT NULL, -- unique identifier for the trade
    account_id character varying(64) NOT NULL, -- investment account executing the trade
    security_id character varying(64) NOT NULL, -- security being traded
    order_id character varying(64), -- related order ID if applicable
    trade_type character varying(10) NOT NULL, -- 'Buy' or 'Sell'
    quantity numeric(19, 8) NOT NULL, -- number of units traded
    price_per_unit numeric(19, 8) NOT NULL, -- price per unit of the security
    total_amount numeric(19, 4) NOT NULL, -- total value of the trade (quantity * price)
    commission numeric(10, 4), -- commission fee charged for the trade
    trade_timestamp timestamp NOT NULL, -- exact time the trade was executed
    settlement_date date, -- date the trade settles
    status character varying(32) NOT NULL, -- e.g., Executed, Settled, Cancelled
    execution_venue character varying(100), -- where the trade was executed
    PRIMARY KEY (trade_id),
    FOREIGN KEY (account_id) REFERENCES financial_services.accounts(account_id),
    FOREIGN KEY (security_id) REFERENCES financial_services.securities(security_id)
)
CREATE TABLE financial_services.market_data (
    data_point_id bigserial NOT NULL, -- auto-incrementing primary key
    security_id character varying(64) NOT NULL, -- identifier for the security
    data_timestamp timestamp NOT NULL, -- timestamp for the data point (e.g., end of day, intraday)
    open_price numeric(19, 8), -- opening price for the period
    high_price numeric(19, 8), -- highest price during the period
    low_price numeric(19, 8), -- lowest price during the period
    close_price numeric(19, 8) NOT NULL, -- closing price for the period
    adjusted_close_price numeric(19, 8), -- closing price adjusted for dividends and splits
    volume bigint, -- trading volume during the period
    source character varying(50), -- source of the market data (e.g., Bloomberg, Refinitiv)
    PRIMARY KEY (data_point_id),
    UNIQUE (security_id, data_timestamp), -- Ensure unique data point per security per time
    FOREIGN KEY (security_id) REFERENCES financial_services.securities(security_id)
)
CREATE TABLE financial_services.employees (
    employee_id character varying(64) NOT NULL,  -- unique identifier for the employee
    first_name character varying(100) NOT NULL,
    last_name character varying(100) NOT NULL,
    job_title character varying(100) NOT NULL, -- e.g., Teller, Branch Manager, Financial Advisor, Analyst
    department character varying(100), -- e.g., Retail Banking, Wealth Management, IT
    branch_id character varying(64), -- Identifier for the branch they work at (if applicable)
    email character varying(128) NOT NULL UNIQUE,
    phone_extension character varying(20),
    hire_date date NOT NULL,
    termination_date date, -- Date of termination, null if currently employed
    manager_id character varying(64), -- Self-referencing key for manager relationship
    status character varying(32) NOT NULL, -- e.g., Active, Terminated, On Leave
    PRIMARY KEY (employee_id),
    FOREIGN KEY (branch_id) REFERENCES financial_services.branches(branch_id), -- Assuming a branches table exists
    FOREIGN KEY (manager_id) REFERENCES financial_services.employees(employee_id)
)


[User] List all ERC20 tokens where the price is greater than $100, including their names and symbols.

[Assistant] SELECT ti.name, ti.symbol FROM token_info ti JOIN token_prices tp ON ti.tick = tp.symbol WHERE tp.price > 100;

[User] I think there's an error in your query - it should be joining on contract_address not symbol. Also, can you add the current price to the results?

[Assistant] SELECT ti.name, ti.symbol, tp.price FROM token_info ti JOIN token_prices tp ON ti.creator = tp.address WHERE tp.price > 100;

[User] Now sort these results by price in descending order and limit to the top 10.

[Assistant] SELECT ti.name, ti.symbol, tp.price FROM token_info ti JOIN token_prices tp ON ti.creator = tp.address WHERE tp.price > 100 ORDER BY tp.price DESC 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 erc1155_approval_for_all (
    block_number bigint NOT NULL, -- Block number containing the transaction
    block_timestamp timestamp(3) NOT NULL, -- Timestamp of the block containing the transaction
    transaction_index integer NOT NULL, -- Index of the transaction within the block
    transaction_hash varchar(66) NOT NULL, -- Transaction hash
    log_index integer NOT NULL, -- Log index
    contract_address varchar(42) NOT NULL  -- Event contract address
)
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 NOT NULL, contract_address varchar NOT NULL, wallet_address varchar NOT NULL, amount varchar NOT NULL, pk integer NOT NULL )
CREATE TABLE nft_holders (
    block_number bigint NOT NULL, -- Block number containing the transaction
    contract_address varchar NOT NULL, -- Event contract address
    wallet_address varchar NOT NULL, -- The wallet address for the contract(with bloom filter)
    token_id varchar NOT NULL, -- NFT token id
    contract_type varchar NOT NULL, -- NFT contract type
    amount varchar NOT NULL, -- Number of held NFTs
    pk varchar NOT NULL  -- The last string partition of the contract.
)
CREATE TABLE nft_holder_historical ( block_number bigint, contract_address text, wallet_address text, token_id text, contract_type text, amount text, pk integer )
CREATE TABLE sui_coins_metadata ( object_id.text, coin_type.text, status.text, decimals.bigint, description.text, icon_url.text, symbol.text, name.text )
CREATE TABLE sui_nfts ( object_id text, status text, collection_type text, package_id text, previous_transaction text, display text, owner text, name text )
CREATE TABLE nft_metadata ( blockchain text, contract_address text, token_id text, contract_name text, erc_type text, amount bigint, minter text, owner text, mint_block_number bigint, mint_time bigint, mint_transaction_hash text, mint_price text, token_uri text, metadata text, name text, image_uri text, traits text, updated_at bigint, status text, rarity_score real, rarity_rank integer, unique_attribute_count integer, pk integer )
CREATE TABLE nft_collections ( blockchain varchar, contract_address varchar, name varchar, symbol varchar, deploy_block_number bigint, deploy_block_time bigint, erc_type varchar, owner varchar, traits varchar, description varchar, slug varchar, media_info varchar, image_url varchar, banner_image_url varchar, updated_at bigint, banner varchar, token_count bigint, floor_price varchar, floor_price_symbol varchar, floor_price_contract varchar, pk integer )
CREATE TABLE token_prices ( uuid.text, blockchain.text, address.text, decimals.bigint, symbol.text, price.real, timestamp.timestamp )
CREATE TABLE erc20_approval ( block_number bigint, block_timestamp timestamp, transaction_index integer, transaction_hash text, log_index integer, contract_address text, pk integer )
CREATE TABLE token_balances ( block_number.bigint, block_timestamp.timestamp, tick.text, wallet_address.text, total_supply.decimal, amount.decimal )
CREATE TABLE token_info (
    block_timestamp timestamp(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_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(3) NOT NULL, block_number bigint NOT NULL, tx_index integer NOT NULL, tx_hash varchar(66) NOT NULL, tick varchar(255) NOT NULL, max_supply decimal(38,0) NOT NULL, lim decimal(38,0) NOT NULL, wlim decimal(38,0) NOT NULL, dec integer NOT NULL, creator varchar(42) NOT NULL )
CREATE TABLE token_activities_bitcoin ( block_timestamp timestamp, block_number bigint, tx_index integer, tx_hash text, log_index integer, type text, tick text, id text, amt decimal, from_address text, to_address text )
CREATE TABLE token_balances_avalanche ( block_number bigint NOT NULL, block_timestamp timestamp(3) NOT NULL, tick varchar(20) NOT NULL, wallet_address varchar(42) NOT NULL, total_supply decimal(38,0) NOT NULL, amount decimal(38,0) NOT NULL )


[User] Show the full names and contact emails of all citizens who have made a payment for an application that is currently in 'Pending' status.

[Assistant]
SELECT DISTINCT c.first_name || ' ' || c.last_name AS full_name, c.contact_email
FROM government_services.citizens c
JOIN government_services.payments p ON c.citizen_id = p.citizen_id
JOIN government_services.applications a ON p.application_id = a.application_id
WHERE a.status = 'Pending';

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 PRIMARY KEY, national_id_number text, first_name text, last_name text, date_of_birth date, gender text, primary_address text, contact_email text, contact_phone text, registration_date timestamp, is_verified boolean )
CREATE TABLE government_services.applications ( application_id text PRIMARY KEY, citizen_id text, service_id text, submitted_at timestamp, status text, last_updated_at timestamp, assigned_employee_id text, decision_date date, notes text, reference_number text )
CREATE TABLE government_services.payments ( payment_id text PRIMARY KEY, application_id text, citizen_id text, service_id text, amount numeric, currency text, payment_method text, payment_provider_reference text, payment_timestamp timestamp, status text, notes text )
CREATE TABLE government_services.service_locations ( location_id text PRIMARY KEY, agency_id text, location_name text, address text, city text, state text, postal_code text, latitude numeric, longitude numeric, operating_hours text, contact_phone text, is_accessible boolean )
CREATE TABLE government_services.appointments ( appointment_id text PRIMARY KEY, citizen_id text, employee_id text, location_id text, service_id text, scheduled_start_time timestamp, scheduled_end_time timestamp, purpose text, status text, booking_method text, created_at timestamp, notes text )
CREATE TABLE government_services.notifications ( notification_id text PRIMARY KEY, citizen_id text, application_id text, message_subject text, message_body text, channel text, sent_at timestamp, status text, related_entity_type text, related_entity_id text )


[User] Count the total number of comments each user has made.

[Assistant] SELECT user_id, COUNT(*) AS comment_count FROM comments GROUP BY user_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 social_media.comments ( comment_id.text, post_id.text, user_id.text, parent_comment_id.text, content.text, created_at.timestamp, updated_at.timestamp )


[User] Find guests who have made at least one payment using a 'CreditCard'. List their full name (first and last name) and email address.

[Assistant] SELECT DISTINCT T1.first_name, T1.last_name, T1.email FROM hospitality_technology.guests AS T1 JOIN hospitality_technology.payments AS T2 ON T1.guest_id = T2.guest_id WHERE T2.payment_method = 'CreditCard';

[User] For these guests, also show the total amount they have paid using a 'CreditCard'.

[Assistant] SELECT T1.first_name, T1.last_name, T1.email, SUM(T2.amount) AS total_credit_card_amount FROM hospitality_technology.guests AS T1 JOIN hospitality_technology.payments AS T2 ON T1.guest_id = T2.guest_id WHERE T2.payment_method = 'CreditCard' GROUP BY T1.guest_id, T1.first_name, T1.last_name, T1.email;

[User] Now, only include guests where the total credit card payment exceeds 5000.

[Assistant] SELECT T1.first_name, T1.last_name, T1.email, SUM(T2.amount) AS total_credit_card_amount FROM hospitality_technology.guests AS T1 JOIN hospitality_technology.payments AS T2 ON T1.guest_id = T2.guest_id WHERE T2.payment_method = 'CreditCard' GROUP BY T1.guest_id, T1.first_name, T1.last_name, T1.email HAVING SUM(T2.amount) > 5000;

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.guests (
    guest_id character varying(64) NOT NULL,  -- unique identifier for the guest profile
    first_name character varying(100) NOT NULL, -- guest's first name
    last_name character varying(100) NOT NULL, -- guest's last name
    email character varying(255) UNIQUE, -- guest's email address (unique identifier?)
    phone_number character varying(30), -- guest's phone number
    date_of_birth date, -- guest's date of birth
    address_line1 character varying(255), -- guest's home address
    city character varying(100),
    state_province character varying(100),
    postal_code character varying(20),
    country_code character varying(3),
    preferences text, -- notes on guest preferences (e.g., allergies, room location)
    loyalty_member_id character varying(64) UNIQUE, -- FK to loyalty_members table
    communication_consent boolean DEFAULT true, -- consent for marketing communications
    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.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)
)