System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE web3.transactions ( transaction_id character varying(64) NOT NULL, from_address character varying(128) NOT NULL, to_address character varying(128), value numeric(38,14) NOT NULL, gas_used integer NOT NULL, gas_price numeric(38,14) NOT NULL, block_number integer NOT NULL, timestamp timestamp NOT NULL, input_data text, status character varying(32) NOT NULL, nonce integer NOT NULL, PRIMARY KEY (transaction_id) )
CREATE TABLE web3.token_transfers (
    transfer_id character varying(64) NOT NULL,  -- unique identifier for the transfer
    token_id character varying(64) NOT NULL, -- identifier of the token being transferred
    from_address character varying(128) NOT NULL, -- address of the sender
    to_address character varying(128) NOT NULL, -- address of the receiver
    value numeric(38,14) NOT NULL, -- amount of tokens transferred
    transaction_id character varying(64) NOT NULL, -- identifier of the transaction containing the transfer
    log_index integer NOT NULL, -- index of the transfer log in the transaction
    PRIMARY KEY (transfer_id)
)

[User] Show the top 5 transactions with the highest number of token transfers, along with their Ethereum value. Include transaction_id, token_transfer_count, and ether_value.

[Assistant]
SELECT
  tt.transaction_id,
  COUNT(tt.transfer_id) AS token_transfer_count,
  t.value AS ether_value
FROM web3.token_transfers tt
JOIN web3.transactions t
  ON tt.transaction_id = t.transaction_id
GROUP BY
  tt.transaction_id,
  t.value
ORDER BY token_transfer_count DESC
LIMIT 5;


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

[User] Get the number of service locations per state.

[Assistant]
SELECT state, COUNT(*) AS location_count
FROM service_locations
GROUP BY state;

[User] Now only include states that have more than 5 service locations.

[Assistant]
SELECT state, COUNT(*) AS location_count
FROM service_locations
GROUP BY state
HAVING location_count > 5;

[User] I got an error: column "location_count" does not exist in HAVING. Correct the query.

[Assistant]
SELECT state, COUNT(*) AS location_count
FROM service_locations
GROUP BY state
HAVING COUNT(*) > 5;

[User] Also, sort the results by the count in descending order.

[Assistant]
SELECT state, COUNT(*) AS location_count
FROM service_locations
GROUP BY state
HAVING COUNT(*) > 5
ORDER BY COUNT(*) DESC;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE 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.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.trades ( trade_id.text, 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.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] List each security’s ticker symbol and the total number of trades executed for it, along with the sum of quantities traded.

[Assistant]
SELECT s.ticker_symbol, COUNT(t.trade_id) AS total_trades, SUM(t.quantity) AS total_quantity
FROM financial_services.securities s
JOIN financial_services.trades t ON s.security_id = t.security_id
GROUP BY s.ticker_symbol;

[User] Show only those securities with more than 10 trades.

[Assistant]
SELECT s.ticker_symbol, COUNT(t.trade_id) AS total_trades, SUM(t.quantity) AS total_quantity
FROM financial_services.securities s
JOIN financial_services.trades t ON s.security_id = t.security_id
GROUP BY s.ticker_symbol
HAVING COUNT(t.trade_id) > 10;

[User] Add the security_name and order the list by total_quantity descending.

[Assistant]
SELECT s.ticker_symbol, s.security_name, COUNT(t.trade_id) AS total_trades, SUM(t.quantity) AS total_quantity
FROM financial_services.securities s
JOIN financial_services.trades t ON s.security_id = t.security_id
GROUP BY s.ticker_symbol, s.security_name
HAVING COUNT(t.trade_id) > 10
ORDER BY total_quantity DESC;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE insurance.insurance_products (
    product_id character varying(64) NOT NULL, -- unique identifier for the insurance product
    product_name character varying(150) NOT NULL, -- name of the insurance product (e.g., 'Comprehensive Auto Insurance')
    product_type character varying(50) NOT NULL, -- category like 'Auto', 'Home', 'Life', 'Health', 'Travel'
    description text, -- detailed description of the product
    base_premium numeric(10, 2) NOT NULL, -- starting premium before adjustments
    coverage_details text, -- details about what is covered (could be JSON or structured text)
    underwriting_rules text, -- rules used for assessing risk and eligibility
    is_active boolean NOT NULL DEFAULT true, -- whether the product is currently offered
    created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
    updated_at timestamp,
    PRIMARY KEY (product_id)
)

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

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


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE legal_services.law_firms ( firm_id text, firm_name text, address text, phone text, website text, founded_date date, managing_partner_id text )
CREATE TABLE legal_services.cases ( case_id 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 text, case_id text, document_name text, document_type text, storage_path text, uploaded_by_lawyer_id text, upload_timestamp timestamp, version integer, description text )
CREATE TABLE legal_services.time_entries ( entry_id text, case_id text, lawyer_id text, date_worked date, hours_spent numeric, billing_rate numeric, description text, is_billable boolean, is_billed boolean, invoice_id text, created_at timestamp )
CREATE TABLE legal_services.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 all billable but unbilled time entries including entry_id, lawyer_id, case_id, date_worked, hours_spent, and billing_rate.

[Assistant]
SELECT entry_id, lawyer_id, case_id, date_worked, hours_spent, billing_rate
FROM legal_services.time_entries
WHERE is_billable = TRUE
  AND is_billed = FALSE;

[User] Actually, include the case_name from the cases table in the results.

[Assistant]
SELECT te.entry_id,
       te.lawyer_id,
       te.case_id,
       c.case_name,
       te.date_worked,
       te.hours_spent,
       te.billing_rate
FROM legal_services.time_entries te
JOIN legal_services.cases c ON te.case_id = c.case_id
WHERE te.is_billable = TRUE
  AND te.is_billed = FALSE;

[User] Also, only show entries for cases with status 'Pending' and order the output by hours_spent descending.

[Assistant]
SELECT te.entry_id,
       te.lawyer_id,
       te.case_id,
       c.case_name,
       te.date_worked,
       te.hours_spent,
       te.billing_rate
FROM legal_services.time_entries te
JOIN legal_services.cases c ON te.case_id = c.case_id
WHERE te.is_billable = TRUE
  AND te.is_billed = FALSE
  AND c.status = 'Pending'
ORDER BY te.hours_spent DESC;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE government_services.citizens (
    citizen_id character varying(64) NOT NULL,  -- unique identifier for the citizen
    national_id_number character varying(128) NOT NULL UNIQUE, -- official national identification number
    first_name character varying(100) NOT NULL,
    last_name character varying(100) NOT NULL,
    date_of_birth date NOT NULL,
    gender character varying(20),
    primary_address text NOT NULL, -- full primary residential address
    contact_email character varying(128) UNIQUE,
    contact_phone character varying(32),
    registration_date timestamp NOT NULL, -- when the citizen profile was created
    is_verified boolean DEFAULT false, -- whether identity has been officially verified
    PRIMARY KEY (citizen_id)
)
CREATE TABLE government_services.agencies ( agency_id text, agency_name text, jurisdiction_level text, primary_contact_email text, main_phone_number text, website_url text, established_date date, parent_agency_id text )
CREATE TABLE government_services.services ( service_id character varying(64) NOT NULL, agency_id character varying(64) NOT NULL, service_name character varying(255) NOT NULL, description text, category character varying(100), eligibility_criteria text, standard_fee numeric(10, 2) DEFAULT 0.00, average_processing_time_days integer, is_active boolean DEFAULT true, online_application_url character varying(255), PRIMARY KEY (service_id) )
CREATE TABLE government_services.documents ( document_id text, application_id text, citizen_id text, document_type text, file_reference text, upload_timestamp timestamp, expiry_date date, verification_status text, verified_by_employee_id text, verification_timestamp timestamp )
CREATE TABLE government_services.payments ( payment_id text, application_id text, citizen_id text, service_id text, amount numeric, currency text, payment_method text, payment_provider_reference text, payment_timestamp timestamp, status text, notes text )
CREATE TABLE government_services.notifications ( notification_id character varying(64) NOT NULL, citizen_id character varying(64) NOT NULL, application_id character varying(64), message_subject character varying(255), message_body text NOT NULL, channel character varying(30) NOT NULL, sent_at timestamp NOT NULL, status character varying(30) NOT NULL, related_entity_type character varying(50), related_entity_id character varying(64), PRIMARY KEY (notification_id) )

[User] How many citizens are marked as not verified?

[Assistant] SELECT COUNT(*) FROM government_services.citizens WHERE is_verified = FALSE;


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

[User] Calculate the total billable hours spent by each lawyer for entries in March 2024.

[Assistant]
SELECT lawyer_id,
       SUM(hours_spent) AS total_hours
FROM legal_services.time_entries
WHERE is_billable = TRUE
  AND date_worked BETWEEN '2024-03-01' AND '2024-03-31'
GROUP BY lawyer_id;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE insurance.insurance_products ( product_id text PRIMARY KEY, product_name text, product_type text, description text, base_premium numeric, coverage_details text, underwriting_rules text, is_active boolean, created_at timestamp, updated_at timestamp )

[User] Show me product_id, product_name, and base_premium for products created after '2023-01-01'.

[Assistant]
SELECT product_id,
       product_name,
       base_premium
FROM insurance.insurance_products
WHERE created_at > '2023-01-01';

[User] Actually, only include those with a base_premium greater than 1000.

[Assistant]
SELECT product_id,
       product_name,
       base_premium
FROM insurance.insurance_products
WHERE created_at > '2023-01-01'
  AND base_premium > 1000;

[User] Can you also order the results by base_premium descending and limit to the top 5?

[Assistant]
SELECT product_id,
       product_name,
       base_premium
FROM insurance.insurance_products
WHERE created_at > '2023-01-01'
  AND base_premium > 1000
ORDER BY base_premium DESC
LIMIT 5;

[User] Now, I need the total number of such products per product_type.

[Assistant]
SELECT product_type,
       COUNT(*) AS product_count
FROM insurance.insurance_products
WHERE created_at > '2023-01-01'
  AND base_premium > 1000
GROUP BY product_type;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE social_media.posts ( post_id text PRIMARY KEY, user_id text, content text, media_url text, media_type text, created_at timestamp, updated_at timestamp, visibility text, location_lat numeric, location_lon numeric )

[User] List all posts where the content mentions 'meeting'.

[Assistant] SELECT post_id, user_id, content, created_at FROM social_media.posts WHERE content LIKE '%meeting%'

[User] Also, only include those posts that are public.

[Assistant] SELECT post_id, user_id, content, created_at FROM social_media.posts WHERE content LIKE '%meeting%' AND visibility = 'public'


[User] Show me the total number of time entries for each case.

[Assistant]
SELECT case_id, COUNT(*) AS entry_count
FROM legal_services.time_entries
GROUP BY case_id;

[User] Only include cases where the total is greater than 10.

[Assistant]
SELECT case_id, COUNT(*) AS entry_count
FROM legal_services.time_entries
GROUP BY case_id
HAVING COUNT(*) > 10;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE government_services.agencies ( agency_id text, agency_name text, jurisdiction_level text, primary_contact_email text, main_phone_number text, website_url text, established_date date, parent_agency_id text )
CREATE TABLE government_services.services ( service_id text, agency_id text, service_name text, description text, category text, eligibility_criteria text, standard_fee numeric, average_processing_time_days integer, is_active boolean, online_application_url text )
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.notifications ( notification_id text, citizen_id text, application_id text, message_subject text, message_body text, channel text, sent_at timestamp, status text, related_entity_type text, related_entity_id text )

[User] Which agencies offer services in the 'Social Assistance' category? Show the agency name and the service name.

[Assistant]
SELECT a.agency_name, s.service_name
FROM government_services.services s
JOIN government_services.agencies a ON s.agency_id = a.agency_id
WHERE s.category = 'Social Assistance';


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE token_basic_info ( coin_id 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 token_dexpool_info ( pair_address character varying(512) NOT NULL, token_name character varying(100) NOT NULL, token_symbol character varying(100) NOT NULL, chain text, price double precision, price_change_percentage_1h double precision, price_change_percentage_6h double precision, price_change_percentage_24h double precision, makers_24h double precision, volume_24h double precision, liquidity double precision, market_cap double precision, trend_rank bigint )
CREATE TABLE smart_money_token_inflow ( token_address character varying(100) NOT NULL, token_symbol character varying(100), token_amount numeric(38,2), usd_value numeric(38,2), avg_price numeric(38,6), type int, address_amount integer, narrative character varying(100), chain character varying(100) )

[User] Show the top 3 tokens on Polygon with the greatest positive price change over the last 6 hours, including their symbol, price, 6h change, and the number of smart money buy addresses in the last 24h.

[Assistant]
SELECT tdi.token_symbol, tdi.price, tdi.price_change_percentage_6h,
  COALESCE(SUM(CASE WHEN smti.type = 1 AND smti.chain = 'Polygon' THEN smti.address_amount ELSE 0 END), 0) AS buy_address_count
FROM token_dexpool_info tdi
LEFT JOIN smart_money_token_inflow smti
  ON tdi.token_symbol = smti.token_symbol AND tdi.chain = smti.chain
WHERE tdi.chain = 'Polygon' AND tdi.price_change_percentage_6h > 0
GROUP BY tdi.token_symbol, tdi.price, tdi.price_change_percentage_6h
ORDER BY tdi.price_change_percentage_6h DESC
LIMIT 3;

[User] Instead of just Polygon, can you show the top 3 tokens with the greatest positive 6h price change across both Polygon and BSC? Still include the number of smart money buys.

[Assistant]
SELECT tdi.token_symbol, tdi.chain, tdi.price, tdi.price_change_percentage_6h,
  COALESCE(SUM(CASE WHEN smti.type = 1 THEN smti.address_amount ELSE 0 END), 0) AS buy_address_count
FROM token_dexpool_info tdi
LEFT JOIN smart_money_token_inflow smti
  ON tdi.token_symbol = smti.token_symbol AND tdi.chain = smti.chain
WHERE tdi.chain IN ('Polygon', 'BSC') AND tdi.price_change_percentage_6h > 0
GROUP BY tdi.token_symbol, tdi.chain, tdi.price, tdi.price_change_percentage_6h
ORDER BY tdi.price_change_percentage_6h DESC
LIMIT 3;

[User] Now, only display tokens with at least 10 smart money buy addresses. Also, add their 24h trading volume.

[Assistant]
SELECT tdi.token_symbol, tdi.chain, tdi.price, tdi.price_change_percentage_6h, tdi.volume_24h,
  COALESCE(SUM(CASE WHEN smti.type = 1 THEN smti.address_amount ELSE 0 END), 0) AS buy_address_count
FROM token_dexpool_info tdi
LEFT JOIN smart_money_token_inflow smti
  ON tdi.token_symbol = smti.token_symbol AND tdi.chain = smti.chain
WHERE tdi.chain IN ('Polygon', 'BSC') AND tdi.price_change_percentage_6h > 0
GROUP BY tdi.token_symbol, tdi.chain, tdi.price, tdi.price_change_percentage_6h, tdi.volume_24h
HAVING COALESCE(SUM(CASE WHEN smti.type = 1 THEN smti.address_amount ELSE 0 END), 0) >= 10
ORDER BY tdi.price_change_percentage_6h DESC
LIMIT 3;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE gaming_technology.players ( player_id.uuid, username.text, email.text, password_hash.text, registration_date.timestamptz, last_login.timestamptz, country_code.text, status.text, profile_data.jsonb )
CREATE TABLE gaming_technology.game_sessions (
    session_id uuid NOT NULL DEFAULT gen_random_uuid(), -- unique identifier for the game session
    player_id uuid NOT NULL, -- FK linking to the players table
    game_id uuid NOT NULL, -- FK linking to the games table
    server_id uuid, -- FK linking to the servers table (nullable for single-player)
    start_time timestamp with time zone NOT NULL DEFAULT CURRENT_TIMESTAMP, -- when the session began
    end_time timestamp with time zone, -- when the session ended (null if ongoing)
    duration_seconds integer, -- calculated duration of the session in seconds
    score integer, -- player's score for the session, if applicable
    session_data jsonb, -- flexible field for session-specific info (e.g., map played, character used)
    PRIMARY KEY (session_id)
    -- FOREIGN KEY (player_id) REFERENCES gaming_technology.players(player_id),
    -- FOREIGN KEY (game_id) REFERENCES gaming_technology.games(game_id),
    -- FOREIGN KEY (server_id) REFERENCES gaming_technology.servers(server_id)
)
CREATE TABLE gaming_technology.servers ( server_id uuid NOT NULL DEFAULT gen_random_uuid(), game_id uuid NOT NULL, server_name character varying(150), region character varying(50) NOT NULL, ip_address character varying(45), port integer, current_players integer NOT NULL DEFAULT 0, max_players integer NOT NULL, status character varying(30) NOT NULL DEFAULT 'offline', last_heartbeat timestamp with time zone, PRIMARY KEY (server_id) )
CREATE TABLE gaming_technology.achievements ( achievement_id uuid, game_id uuid, name text, description text, icon_url text, points integer, hidden boolean )
CREATE TABLE gaming_technology.player_achievements ( player_achievement_id.uuid, player_id.uuid, achievement_id.uuid, unlocked_at.timestamptz )
CREATE TABLE gaming_technology.in_game_items ( item_id uuid NOT NULL DEFAULT gen_random_uuid(), game_id uuid NOT NULL, item_name character varying(150) NOT NULL, item_type character varying(50) NOT NULL, description text, rarity character varying(30), cost_currency character varying(10), cost_amount numeric(12, 2), attributes jsonb, PRIMARY KEY (item_id) )

[User] For each player, show their player_id and the number of unique games they have played sessions on.

[Assistant]
SELECT player_id, COUNT(DISTINCT game_id) AS unique_games
FROM gaming_technology.game_sessions
GROUP BY player_id;

[User] Also show the total number of sessions they have played.

[Assistant]
SELECT player_id, COUNT(DISTINCT game_id) AS unique_games, COUNT(*) AS total_sessions
FROM gaming_technology.game_sessions
GROUP BY player_id;

[User] Only include players who have played on more than 2 unique games.

[Assistant]
SELECT player_id, COUNT(DISTINCT game_id) AS unique_games, COUNT(*) AS total_sessions
FROM gaming_technology.game_sessions
GROUP BY player_id
HAVING COUNT(DISTINCT game_id) > 2;

[User] For each result, include the player's username as well.

[Assistant]
SELECT p.player_id, p.username, COUNT(DISTINCT gs.game_id) AS unique_games, COUNT(*) AS total_sessions
FROM gaming_technology.players p
JOIN gaming_technology.game_sessions gs ON p.player_id = gs.player_id
GROUP BY p.player_id, p.username
HAVING COUNT(DISTINCT gs.game_id) > 2;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE 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] Show the latest version number of each document_name for every case.

[Assistant]
SELECT case_id,
       document_name,
       MAX(version) AS latest_version
FROM legal_services.documents
GROUP BY case_id, document_name;

[User] Actually, I also need the upload_timestamp of that latest version.

[Assistant]
SELECT d.case_id,
       d.document_name,
       d.version AS latest_version,
       d.upload_timestamp
FROM legal_services.documents d
JOIN (
  SELECT case_id,
         document_name,
         MAX(version) AS latest_version
  FROM legal_services.documents
  GROUP BY case_id, document_name
) sub
  ON d.case_id = sub.case_id
 AND d.document_name = sub.document_name
 AND d.version = sub.latest_version;

[User] Also include the uploaded_by_lawyer_id for each latest version.

[Assistant]
SELECT d.case_id,
       d.document_name,
       d.version AS latest_version,
       d.upload_timestamp,
       d.uploaded_by_lawyer_id
FROM legal_services.documents d
JOIN (
  SELECT case_id,
         document_name,
         MAX(version) AS latest_version
  FROM legal_services.documents
  GROUP BY case_id, document_name
) sub
  ON d.case_id = sub.case_id
 AND d.document_name = sub.document_name
 AND d.version = sub.latest_version;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE manufacturing.materials (
    material_id character varying(64) NOT NULL,  -- unique identifier for the material
    material_name character varying(128) NOT NULL, -- common name (e.g., Titanium Alloy Grade 5, Carbon Fiber Prepreg)
    specification character varying(255), -- specification standard (e.g., AMS 4928)
    description text, -- detailed description of properties
    density_kg_m3 numeric(10, 4), -- density in kg per cubic meter
    tensile_strength_mpa integer, -- tensile strength in Megapascals
    PRIMARY KEY (material_id)
)
CREATE TABLE manufacturing.assembly_steps (
    step_id character varying(64) NOT NULL, -- unique identifier for an assembly step/task
    line_id character varying(64) NOT NULL, -- FK to the assembly line where this step occurs
    step_number integer NOT NULL, -- sequence number of the step on the line
    step_name character varying(255) NOT NULL, -- name of the task (e.g., Install Wing Root Fairing)
    description text, -- detailed instructions or description
    standard_duration_hours numeric(8,2), -- estimated time to complete the step
    required_skill_level character varying(50), -- skill level needed (e.g., 'Mechanic II', 'Electrician I')
    workstation character varying(100), -- specific workstation or area for the step
    PRIMARY KEY (step_id)
)

[User] 特定の材料を使用しているコンポーネントの組み立て手順を確認したいです。材料IDと材料名、組み立て手順のステップ名と説明を含めてください。

[Assistant]
SELECT m.material_id, m.material_name, s.step_name, s.description
FROM manufacturing.materials m
JOIN manufacturing.assembly_steps s ON m.material_id = s.step_id
WHERE m.material_id = 'specific_material_id';

[User] さらに、特定のスキルレベルが必要な手順だけを表示するようにできますか？例えば「Mechanic II」のみ。

[Assistant]
SELECT m.material_id, m.material_name, s.step_name, s.description
FROM manufacturing.materials m
JOIN manufacturing.assembly_steps s ON m.material_id = s.step_id
WHERE m.material_id = 'specific_material_id'
AND s.required_skill_level = 'Mechanic II';

[User] もし標準作業時間が2時間以上の手順だけを絞り込みたい場合はどうすればいいですか？

[Assistant]
SELECT m.material_id, m.material_name, s.step_name, s.description
FROM manufacturing.materials m
JOIN manufacturing.assembly_steps s ON m.material_id = s.step_id
WHERE m.material_id = 'specific_material_id'
AND s.required_skill_level = 'Mechanic II'
AND s.standard_duration_hours >= 2;

[User] 最後に、ステップ番号順に並べ替えて結果を表示してください。

[Assistant]
SELECT m.material_id, m.material_name, s.step_name, s.description
FROM manufacturing.materials m
JOIN manufacturing.assembly_steps s ON m.material_id = s.step_id
WHERE m.material_id = 'specific_material_id'
AND s.required_skill_level = 'Mechanic II'
AND s.standard_duration_hours >= 2
ORDER BY s.step_number;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE gaming_technology.achievements ( achievement_id uuid, game_id uuid, name text, description text, icon_url text, points integer, hidden boolean )

[User] How many visible achievements are there per game, and what is the average point value of these achievements?

[Assistant]
SELECT game_id, COUNT(*) AS visible_count, AVG(points) AS avg_points
FROM gaming_technology.achievements
WHERE hidden = FALSE
GROUP BY game_id;

[User] Only include games that have more than 5 visible achievements.

[Assistant]
SELECT game_id, COUNT(*) AS visible_count, AVG(points) AS avg_points
FROM gaming_technology.achievements
WHERE hidden = FALSE
GROUP BY game_id
HAVING COUNT(*) > 5;

[User] Also filter to games where the average points is greater than 30.

[Assistant]
SELECT game_id, COUNT(*) AS visible_count, AVG(points) AS avg_points
FROM gaming_technology.achievements
WHERE hidden = FALSE
GROUP BY game_id
HAVING COUNT(*) > 5 AND AVG(points) > 30;

[User] Sort the results by average points in descending order.

[Assistant]
SELECT game_id, COUNT(*) AS visible_count, AVG(points) AS avg_points
FROM gaming_technology.achievements
WHERE hidden = FALSE
GROUP BY game_id
HAVING COUNT(*) > 5 AND AVG(points) > 30
ORDER BY avg_points DESC;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE 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 text, token_name text, token_symbol text, token_address text, chain text, price numeric, price_change_percentage_1h numeric, price_change_percentage_24h numeric, price_change_percentage_7d numeric, highest_price_24h numeric, lowest_price_24h numeric, market_cap numeric, market_cap_rank numeric, market_cap_change_percentage_24h text, total_volume text, narrative text, trend_rank numeric )
CREATE TABLE token_dexpool_info ( pair_address text, token_name text, token_symbol text, chain text, price numeric, price_change_percentage_1h numeric, price_change_percentage_6h numeric, price_change_percentage_24h numeric, makers_24h numeric, volume_24h numeric, liquidity numeric, market_cap numeric, trend_rank numeric )
  "CREATE TABLE cex_token_balance (",
    "snapshot_time character varying(32) NOT NULL,  -- the snapshot time of record, converted from original timestamp",
    "chain character varying(128) NOT NULL, -- the chain that the token resides",
    "address character varying(128) NOT NULL, -- the address that holds the assets, owned by a CEX",
    "exchange character varying(512) NOT NULL, -- a centralized exchange name",
    "token_address character varying(128) NOT NULL, -- token contract address",
    "token_symbol character varying(512), --token symbol",
    "balance numeric(38,10), -- token balance",
    "usd_value numeric(38,14), -- value of the token held in USD",
    "price double precision, --price of the token in USD",
    ",PRIMARY KEY (snapshot_time, exchange, address, chain, token_address));"

[User] List all tokens held by CEX addresses, showing the token symbol, name, current price, and the total USD value held by all CEXes for that token.

[Assistant] SELECT T1.token_symbol, T1.token_name, T1.price, SUM(T2.usd_value) AS total_cex_usd_value FROM token_basic_info AS T1 INNER JOIN cex_token_balance AS T2 ON T1.token_symbol = T2.token_symbol GROUP BY T1.token_symbol, T1.token_name, T1.price

[User] Only show results for tokens on the 'Ethereum' chain and order them by the total CEX USD value descending.

[Assistant] SELECT T1.token_symbol, T1.token_name, T1.price, SUM(T2.usd_value) AS total_cex_usd_value FROM token_basic_info AS T1 INNER JOIN cex_token_balance AS T2 ON T1.token_symbol = T2.token_symbol WHERE T1.chain = 'Ethereum' GROUP BY T1.token_symbol, T1.token_name, T1.price ORDER BY total_cex_usd_value DESC

[User] Add a filter to only include tokens where the total CEX USD value is greater than 1,000,000.

[Assistant] SELECT T1.token_symbol, T1.token_name, T1.price, SUM(T2.usd_value) AS total_cex_usd_value FROM token_basic_info AS T1 INNER JOIN cex_token_balance AS T2 ON T1.token_symbol = T2.token_symbol WHERE T1.chain = 'Ethereum' GROUP BY T1.token_symbol, T1.token_name, T1.price HAVING SUM(T2.usd_value) > 1000000 ORDER BY total_cex_usd_value DESC

[User] Limit the results to the top 5 tokens.

[Assistant] SELECT T1.token_symbol, T1.token_name, T1.price, SUM(T2.usd_value) AS total_cex_usd_value FROM token_basic_info AS T1 INNER JOIN cex_token_balance AS T2 ON T1.token_symbol = T2.token_symbol WHERE T1.chain = 'Ethereum' GROUP BY T1.token_symbol, T1.token_name, T1.price HAVING SUM(T2.usd_value) > 1000000 ORDER BY total_cex_usd_value DESC LIMIT 5


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE hospitality_technology.properties (
    property_id character varying(64) NOT NULL,  -- unique identifier for the property (hotel, resort, etc.)
    property_name character varying(255) NOT NULL, -- name of the property
    address_line1 character varying(255) NOT NULL, -- primary address line
    address_line2 character varying(255), -- secondary address line
    city character varying(100) NOT NULL, -- city
    state_province character varying(100), -- state or province
    postal_code character varying(20) NOT NULL, -- zip or postal code
    country_code character varying(3) NOT NULL, -- ISO country code (e.g., USA, CAN)
    phone_number character varying(30), -- main contact phone
    email_address character varying(255), -- main contact email
    property_type character varying(50) NOT NULL, -- e.g., Hotel, Resort, B&B, Motel
    star_rating numeric(2,1), -- star rating (e.g., 4.5)
    timezone character varying(64) NOT NULL, -- IANA timezone ID (e.g., America/New_York)
    manager_staff_id character varying(64), -- FK to staff table for the general manager
    created_at timestamp with time zone NOT NULL DEFAULT current_timestamp, -- record creation time
    updated_at timestamp with time zone NOT NULL DEFAULT current_timestamp, -- record last update time
    PRIMARY KEY (property_id)
)
CREATE TABLE hospitality_technology.rooms (
    room_id character varying(64) NOT NULL,  -- unique identifier for the room
    property_id character varying(64) NOT NULL, -- FK to properties table
    room_number character varying(10) NOT NULL, -- room number identifier (e.g., '101', 'Suite 2B')
    room_type_id character varying(64) NOT NULL, -- FK to room_types table
    floor integer, -- floor number the room is on
    status character varying(50) NOT NULL, -- e.g., Available, Occupied, Cleaning, OutOfOrder, Maintenance
    is_smoking boolean NOT NULL DEFAULT false, -- smoking allowed flag
    features text, -- description of features (e.g., Balcony, Sea View, Jacuzzi)
    current_condition text, -- notes on room condition
    last_cleaned_at timestamp with time zone, -- timestamp of last cleaning
    PRIMARY KEY (room_id),
    FOREIGN KEY (property_id) REFERENCES hospitality_technology.properties(property_id),
    FOREIGN KEY (room_type_id) REFERENCES hospitality_technology.room_types(room_type_id)
)
CREATE TABLE hospitality_technology.guests ( guest_id character varying(64) NOT NULL, first_name character varying(100) NOT NULL, last_name character varying(100) NOT NULL, email character varying(255) UNIQUE, phone_number character varying(30), date_of_birth date, address_line1 character varying(255), city character varying(100), state_province character varying(100), postal_code character varying(20), country_code character varying(3), preferences text, loyalty_member_id character varying(64) UNIQUE, communication_consent boolean DEFAULT true, created_at timestamp with time zone NOT NULL DEFAULT current_timestamp, updated_at timestamp with time zone NOT NULL DEFAULT current_timestamp, PRIMARY KEY (guest_id) )
CREATE TABLE hospitality_technology.reservations ( reservation_id text, property_id text, guest_id text, room_id text, room_type_id text, check_in_date date, check_out_date date, actual_check_in_ts timestamp, actual_check_out_ts timestamp, num_adults integer, num_children integer, status text, booking_source text, rate_plan_id text, total_amount numeric, amount_paid numeric, special_requests text, created_at timestamp, updated_at timestamp )
CREATE TABLE hospitality_technology.staff (
    staff_id character varying(64) NOT NULL,  -- unique identifier for the staff member
    property_id character varying(64) NOT NULL, -- FK to properties table (primary property)
    first_name character varying(100) NOT NULL,
    last_name character varying(100) NOT NULL,
    position character varying(100) NOT NULL, -- e.g., Front Desk Agent, Housekeeper, Manager, Concierge
    work_email character varying(255) UNIQUE, -- staff member's work email
    work_phone character varying(30),
    hire_date date NOT NULL,
    termination_date date, -- date employment ended (if applicable)
    is_active boolean NOT NULL DEFAULT true, -- currently employed flag
    access_level integer NOT NULL, -- permission level within systems (e.g., 1=basic, 5=admin)
    manager_id character varying(64), -- FK to staff table (self-referencing for supervisor)
    created_at timestamp with time zone NOT NULL DEFAULT current_timestamp,
    PRIMARY KEY (staff_id),
    FOREIGN KEY (property_id) REFERENCES hospitality_technology.properties(property_id),
    FOREIGN KEY (manager_id) REFERENCES hospitality_technology.staff(staff_id)
)
CREATE TABLE hospitality_technology.services ( service_id character varying(64) NOT NULL, property_id character varying(64) NOT NULL, service_name character varying(150) NOT NULL, description text, category character varying(100), price numeric(10, 2) NOT NULL, unit character varying(30), is_available boolean NOT NULL DEFAULT true, department character varying(100), PRIMARY KEY (service_id), FOREIGN KEY (property_id) REFERENCES hospitality_technology.properties(property_id) )
CREATE TABLE hospitality_technology.service_orders ( order_id text, reservation_id text, guest_id text, service_id text, staff_id_ordered text, staff_id_delivered text, order_timestamp timestamp, delivery_timestamp timestamp, quantity integer, unit_price numeric, total_price numeric, status text, notes text, bill_id text )
CREATE TABLE hospitality_technology.payments (
    payment_id character varying(64) NOT NULL,  -- unique identifier for the payment transaction
    reservation_id character varying(64), -- FK to reservations (if payment is for a stay)
    guest_id character varying(64) NOT NULL, -- FK to guests (who paid)
    bill_id character varying(64), -- FK to bills/invoices this payment applies to
    amount numeric(12,2) NOT NULL, -- amount of the payment
    currency_code character varying(3) NOT NULL, -- ISO currency code (e.g., USD, EUR)
    payment_method character varying(50) NOT NULL, -- e.g., CreditCard, Cash, BankTransfer, Points, Voucher
    card_type character varying(50), -- e.g., Visa, MasterCard, Amex (if CC)
    card_last_four character varying(4), -- last 4 digits of CC (if CC)
    transaction_ref character varying(128), -- reference ID from payment gateway or processor
    payment_timestamp timestamp with time zone NOT NULL DEFAULT current_timestamp, -- when the payment occurred
    status character varying(50) NOT NULL, -- e.g., Pending, Succeeded, Failed, Refunded, Disputed
    staff_id_processed character varying(64), -- FK to staff (who processed the payment)
    notes text, -- notes about the payment
    PRIMARY KEY (payment_id),
    FOREIGN KEY (reservation_id) REFERENCES hospitality_technology.reservations(reservation_id),
    FOREIGN KEY (guest_id) REFERENCES hospitality_technology.guests(guest_id),
    FOREIGN KEY (staff_id_processed) REFERENCES hospitality_technology.staff(staff_id)
)
CREATE TABLE hospitality_technology.reviews ( review_id text PRIMARY KEY, property_id text, reservation_id text, guest_id text, rating_overall int, rating_cleanliness int, rating_service int, rating_location int, rating_value int, comment text, review_source text, review_date timestamp, is_public boolean, staff_response text, response_staff_id text, response_date timestamp )

[User] List each property with the count of rooms that are currently marked as 'Occupied', including the property_name and occupied_count.

[Assistant]
SELECT p.property_name, COUNT(r.room_id) AS occupied_count
FROM properties p
JOIN rooms r ON p.property_id = r.property_id
WHERE r.status = 'Occupied'
GROUP BY p.property_name
HAVING COUNT(r.room_id) > 0;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE gaming_technology.servers ( server_id uuid, game_id uuid, server_name text, region text, ip_address text, port integer, current_players integer, max_players integer, status text, last_heartbeat timestamp with time zone )

[User] Find pairs of servers that are currently 'online' and share the same game_id, listing their server names and the shared game_id.

[Assistant] SELECT s1.server_name AS server1_name, s2.server_name AS server2_name, s1.game_id FROM gaming_technology.servers s1 JOIN gaming_technology.servers s2 ON s1.game_id = s2.game_id AND s1.server_id < s2.server_id WHERE s1.status = 'online' AND s2.status = 'online';

[User] For these pairs, show the sum of their current_players and the sum of their max_players.

[Assistant] SELECT s1.server_name AS server1_name, s2.server_name AS server2_name, s1.game_id, (s1.current_players + s2.current_players) AS combined_current_players, (s1.max_players + s2.max_players) AS combined_max_players FROM gaming_technology.servers s1 JOIN gaming_technology.servers s2 ON s1.game_id = s2.game_id AND s1.server_id < s2.server_id WHERE s1.status = 'online' AND s2.status = 'online';

[User] Order the results by game_id and then by the combined current players in descending order.

[Assistant] SELECT s1.server_name AS server1_name, s2.server_name AS server2_name, s1.game_id, (s1.current_players + s2.current_players) AS combined_current_players, (s1.max_players + s2.max_players) AS combined_max_players FROM gaming_technology.servers s1 JOIN gaming_technology.servers s2 ON s1.game_id = s2.game_id AND s1.server_id < s2.server_id WHERE s1.status = 'online' AND s2.status = 'online' ORDER BY s1.game_id, combined_current_players DESC;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE government_services.documents ( document_id.text, application_id.text, citizen_id.text, document_type.text, file_reference.text, upload_timestamp.timestamp, expiry_date.date, verification_status.text, verified_by_employee_id.text, verification_timestamp.timestamp )

[User] For each document verified by an employee, list the document ID, the name of the verifying employee, and the name of the agency the employee belongs to.

[Assistant] SELECT T1.document_id, T2.first_name, T2.last_name, T3.agency_name FROM government_services.documents AS T1 JOIN government_services.employees AS T2 ON T1.verified_by_employee_id = T2.employee_id JOIN government_services.agencies AS T3 ON T2.agency_id = T3.agency_id;

[User] Only include documents where the verification status is 'Verified' and the agency's jurisdiction level is 'Federal'.

[Assistant] SELECT T1.document_id, T2.first_name, T2.last_name, T3.agency_name FROM government_services.documents AS T1 JOIN government_services.employees AS T2 ON T1.verified_by_employee_id = T2.employee_id JOIN government_services.agencies AS T3 ON T2.agency_id = T3.agency_id WHERE T1.verification_status = 'Verified' AND T3.jurisdiction_level = 'Federal';


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE web3.transactions ( transaction_id text, from_address text, to_address text, value numeric, gas_used integer, gas_price numeric, block_number integer, timestamp timestamp, input_data text, status text, nonce integer )

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

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


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE token_metas ( block_timestamp timestamp, block_number bigint, transaction_hash text, transaction_index bigint, from_address text, contract_address text, symbol text, total_supply text, name text, decimals bigint, is_erc20 integer, is_erc721 integer, is_erc1155 integer, is_proxy integer, extra_info text, pk integer )
CREATE TABLE erc20_balances ( block_number bigint, contract_address text, wallet_address text, amount text, pk text )
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 text, status text, coin_type text, balance text, owner text )
CREATE TABLE sui_coins_metadata ( object_id text, coin_type text, status text, decimals bigint, description text, icon_url text, symbol text, name text )
CREATE TABLE sui_nfts ( object_id text, status text, collection_type text, package_id text, previous_transaction text, display text, owner text, name text )
CREATE TABLE nft_collections ( blockchain text, contract_address text, name text, symbol text, deploy_block_number bigint, deploy_block_time bigint, erc_type text, owner text, traits text, description text, slug text, media_info text, image_url text, banner_image_url text, updated_at bigint, banner text, token_count bigint, floor_price text, floor_price_symbol text, floor_price_contract text, pk integer )
CREATE TABLE token_balances ( block_number bigint, block_timestamp timestamp, tick text, wallet_address text, total_supply decimal, amount decimal )
CREATE TABLE token_activities ( block_timestamp timestamp, block_number bigint, tx_index integer, tx_hash text, log_index integer, type text, tick text, id text, amt decimal, from_address text, to_address text )
CREATE TABLE mud_holesky_redstone ( address text, table_id text, key_bytes text, key0 text, key1 text, static_data text, encoded_lengths text, dynamic_data text, is_deleted boolean, block_number bigint, log_index bigint )
CREATE TABLE token_balances_bitcoin ( block_number bigint, block_timestamp timestamp, tick text, wallet_address text, total_supply text, amount text )
CREATE TABLE token_info_bitcoin ( block_timestamp timestamp, block_number bigint, tx_index integer, tx_hash text, tick text, max_supply decimal, lim decimal, wlim decimal, dec integer, creator text )
CREATE TABLE token_activities_avalanche ( block_timestamp timestamp, block_number bigint, tx_index integer, tx_hash text, log_index integer, type text, tick text, id text, amt decimal, from_address text, to_address text )
CREATE TABLE token_balances_avalanche ( block_number bigint, block_timestamp timestamp, tick text, wallet_address text, total_supply decimal, amount decimal )
CREATE TABLE token_info_avalanche ( block_timestamp timestamp, block_number bigint, tx_index integer, tx_hash text, tick text, max_supply decimal, lim decimal, wlim decimal, dec integer, creator text, minted decimal, holders decimal, txs decimal, updated_timestamp timestamp, completed_timestamp timestamp, id text )

[User] List all ERC20 tokens from the `token_metas` table that have a total supply greater than 1 followed by 21 zeros. Show their contract address, symbol, name, and total supply.

[Assistant] SELECT contract_address, symbol, name, total_supply FROM token_metas WHERE is_erc20 = 1 AND CAST(total_supply AS DECIMAL) > 1000000000000000000000;

[User] Okay, for those tokens, can you also include the number of unique wallet addresses that hold each token? Only show tokens with more than 500 unique holders.

[Assistant] SELECT tm.contract_address, tm.symbol, tm.name, tm.total_supply, COUNT(DISTINCT eb.wallet_address) AS unique_holder_count FROM token_metas tm JOIN erc20_balances eb ON tm.contract_address = eb.contract_address WHERE tm.is_erc20 = 1 AND CAST(tm.total_supply AS DECIMAL) > 1000000000000000000000 GROUP BY tm.contract_address, tm.symbol, tm.name, tm.total_supply HAVING COUNT(DISTINCT eb.wallet_address) > 500;

[User] Great, now add the latest USD price and decimals for these tokens by joining with the `token_prices_latest` table.

[Assistant] SELECT tm.contract_address, tm.symbol, tm.name, tm.total_supply, tpl.usd_price, tm.decimals, COUNT(DISTINCT eb.wallet_address) AS unique_holder_count FROM token_metas tm JOIN erc20_balances eb ON tm.contract_address = eb.contract_address JOIN token_prices_latest tpl ON tm.contract_address = tpl.contract_address WHERE tm.is_erc20 = 1 AND CAST(tm.total_supply AS DECIMAL) > 1000000000000000000000 GROUP BY tm.contract_address, tm.symbol, tm.name, tm.total_supply, tpl.usd_price, tm.decimals HAVING COUNT(DISTINCT eb.wallet_address) > 500;

[User] Please filter the results to only include tokens where the latest price is greater than 0.1 USD, order by the number of unique holders descending, and limit the output to the top 10 tokens.

[Assistant] SELECT tm.contract_address, tm.symbol, tm.name, tm.total_supply, tpl.usd_price, tm.decimals, COUNT(DISTINCT eb.wallet_address) AS unique_holder_count FROM token_metas tm JOIN erc20_balances eb ON tm.contract_address = eb.contract_address JOIN token_prices_latest tpl ON tm.contract_address = tpl.contract_address WHERE tm.is_erc20 = 1 AND CAST(tm.total_supply AS DECIMAL) > 1000000000000000000000 AND tpl.usd_price > 0.1 GROUP BY tm.contract_address, tm.symbol, tm.name, tm.total_supply, tpl.usd_price, tm.decimals HAVING COUNT(DISTINCT eb.wallet_address) > 500 ORDER BY unique_holder_count DESC LIMIT 10;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE hospitality_technology.staff ( staff_id text PRIMARY KEY, property_id text, first_name text, last_name text, position text, work_email text, work_phone text, hire_date date, termination_date date, is_active boolean, access_level int, manager_id text, created_at timestamp )

[User] List staff members who were hired in the last calendar year, showing their full name, position, and hire date.

[Assistant] SELECT first_name, last_name, position, hire_date FROM hospitality_technology.staff WHERE hire_date >= date_trunc('year', current_date - interval '1' year) AND hire_date < date_trunc('year', current_date);

[User] Now, only include those staff members who are not managers and have an access level greater than 3.

[Assistant] SELECT first_name, last_name, position, hire_date FROM hospitality_technology.staff WHERE hire_date >= date_trunc('year', current_date - interval '1' year) AND hire_date < date_trunc('year', current_date) AND position != 'Manager' AND access_level > 3;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE insurance.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_line1 character varying(255) NOT NULL,
    address_line2 character varying(255),
    city character varying(100) NOT NULL,
    state character varying(50) NOT NULL,
    zip_code character varying(20) NOT NULL,
    country character varying(50) NOT NULL DEFAULT 'USA',
    phone_number character varying(30),
    email character varying(128) UNIQUE, -- unique email address
    created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, -- when the customer record was created
    updated_at timestamp, -- when the customer record was last updated
    status character varying(20) NOT NULL DEFAULT 'Active', -- e.g., Active, Inactive, Prospect
    PRIMARY KEY (customer_id)
)
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 )
CREATE TABLE insurance.agents ( agent_id character varying(64) NOT NULL, first_name character varying(100) NOT NULL, last_name character varying(100) NOT NULL, agency_name character varying(150), license_number character varying(100) NOT NULL UNIQUE, license_state character varying(50) NOT NULL, contact_email character varying(128) UNIQUE, contact_phone character varying(30), hire_date date, termination_date date, status character varying(20) NOT NULL DEFAULT 'Active', commission_rate numeric(5, 4) NOT NULL DEFAULT 0.05, manager_id character varying(64), PRIMARY KEY (agent_id) )
CREATE TABLE insurance.policy_beneficiaries ( beneficiary_id character varying(64) NOT NULL, policy_id character varying(64) NOT NULL, customer_id character varying(64) NOT NULL, first_name character varying(100) NOT NULL, last_name character varying(100) NOT NULL, relationship character varying(50) NOT NULL, percentage_share numeric(5, 2) NOT NULL CHECK (percentage_share > 0 AND percentage_share <= 100), contact_info text, added_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, PRIMARY KEY (beneficiary_id), UNIQUE (policy_id, customer_id) )

[User] I need to find, for each active agent, the number of active policies they have sold and the average premium_amount of those active policies.

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

[User] Actually, restrict this to agents licensed in state 'CA'.

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

[User] Also include the average coverage_limit of those policies as avg_coverage_limit.

[Assistant]
SELECT a.agent_id, a.first_name || ' ' || a.last_name AS agent_name, COUNT(p.policy_id) AS policy_count, AVG(p.premium_amount) AS avg_premium_amount, AVG(p.coverage_limit) AS avg_coverage_limit
FROM insurance.agents a
JOIN insurance.policies p ON a.agent_id = p.agent_id
WHERE a.status = 'Active'
  AND p.status = 'Active'
  AND a.license_state = 'CA'
GROUP BY a.agent_id, agent_name
ORDER BY policy_count DESC;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE legal_services.cases ( case_id text, case_number text, case_name text, client_id text, lead_lawyer_id text, case_type text, status text, date_opened timestamp, date_closed timestamp, description text, court_jurisdiction text )

[User] Find all cases that were closed in the year 2022, showing their case name, case number, and date closed.

[Assistant] SELECT case_name, case_number, date_closed FROM legal_services.cases WHERE date_closed >= '2022-01-01' AND date_closed < '2023-01-01';


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE trading_platform.users ( user_id character varying(64) NOT NULL, username character varying(128) NOT NULL, email character varying(128) NOT NULL, password_hash text NOT NULL, created_at timestamp NOT NULL, PRIMARY KEY (user_id) )
CREATE TABLE trading_platform.wallets ( wallet_id character varying(64) NOT NULL, user_id character varying(64) NOT NULL, address character varying(128) NOT NULL, private_key text NOT NULL, created_at timestamp NOT NULL, PRIMARY KEY (wallet_id) )
CREATE TABLE trading_platform.orders ( order_id text PRIMARY KEY, user_id text, wallet_id text, asset_id text, order_type text, quantity numeric, price numeric, status text, created_at timestamp )
CREATE TABLE trading_platform.trades (
    trade_id character varying(64) NOT NULL,  -- unique identifier for the trade
    order_id character varying(64) NOT NULL, -- identifier of the order that led to the trade
    buyer_id character varying(64) NOT NULL, -- identifier of the buyer
    seller_id character varying(64) NOT NULL, -- identifier of the seller
    asset_id character varying(64) NOT NULL, -- identifier of the asset being traded
    quantity numeric(38,14) NOT NULL, -- quantity of the asset in the trade
    price numeric(38,14) NOT NULL, -- price per unit of the asset
    traded_at timestamp NOT NULL, -- time when the trade was executed
    PRIMARY KEY (trade_id)
)
CREATE TABLE trading_platform.assets ( asset_id text PRIMARY KEY, name text, symbol text, type text )
CREATE TABLE trading_platform.dapps ( dapp_id.text, name.text, description.text, url.text )
CREATE TABLE trading_platform.metadata (
    metadata_id character varying(64) NOT NULL,  -- unique identifier for the metadata
    asset_id character varying(64) NOT NULL, -- identifier of the asset the metadata is associated with
    key character varying(128) NOT NULL, -- key of the metadata
    value text NOT NULL, -- value of the metadata
    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,  -- unique identifier for the log entry
    user_id character varying(64), -- identifier of the user associated with the log entry
    action character varying(128) NOT NULL, -- action performed
    details text NOT NULL, -- details of the action
    logged_at timestamp NOT NULL, -- time when the log entry was created
    PRIMARY KEY (log_id)
)
CREATE TABLE trading_platform.notifications ( notification_id text PRIMARY KEY, user_id text, message text, sent_at timestamp, read_at timestamp )

[User] I want a list of all users, showing for each user their user_id, username, KYC status, and the date their account was created.

[Assistant]
SELECT u.user_id, u.username, k.status AS kyc_status, u.created_at
FROM trading_platform.users u
LEFT JOIN trading_platform.kyc_audit k ON u.user_id = k.user_id;

[User] Could you only show users whose KYC status is 'approved'?

[Assistant]
SELECT u.user_id, u.username, k.status AS kyc_status, u.created_at
FROM trading_platform.users u
LEFT JOIN trading_platform.kyc_audit k ON u.user_id = k.user_id
WHERE k.status = 'approved';

[User] Now, add the number of wallets associated with each of these users.

[Assistant]
SELECT u.user_id, u.username, k.status AS kyc_status, u.created_at, COUNT(w.wallet_id) AS wallet_count
FROM trading_platform.users u
LEFT JOIN trading_platform.kyc_audit k ON u.user_id = k.user_id
LEFT JOIN trading_platform.wallets w ON u.user_id = w.user_id
WHERE k.status = 'approved'
GROUP BY u.user_id, u.username, k.status, u.created_at;

[User] Only show users who have more than one wallet, and order the list by wallet_count descending.

[Assistant]
SELECT u.user_id, u.username, k.status AS kyc_status, u.created_at, COUNT(w.wallet_id) AS wallet_count
FROM trading_platform.users u
LEFT JOIN trading_platform.kyc_audit k ON u.user_id = k.user_id
LEFT JOIN trading_platform.wallets w ON u.user_id = w.user_id
WHERE k.status = 'approved'
GROUP BY u.user_id, u.username, k.status, u.created_at
HAVING COUNT(w.wallet_id) > 1
ORDER BY wallet_count DESC;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE insurance.premium_payments ( payment_id character varying(64) NOT NULL, policy_id character varying(64) NOT NULL, customer_id character varying(64) NOT NULL, payment_date timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, amount_paid numeric(12, 2) NOT NULL, payment_method character varying(50), transaction_reference character varying(128) UNIQUE, due_date date, payment_period_start date, payment_period_end date, status character varying(30) NOT NULL DEFAULT 'Completed', PRIMARY KEY (payment_id) )

[User] Show me all premium payments made by customer with ID 'CUST789'.

[Assistant] SELECT * FROM insurance.premium_payments WHERE customer_id = 'CUST789';

[User] From those payments, only include the ones with status 'Completed'.

[Assistant] SELECT * FROM insurance.premium_payments WHERE customer_id = 'CUST789' AND status = 'Completed';

[User] Also, filter the results to only show payments made between '2023-01-01' and '2023-12-31'.

[Assistant] SELECT * FROM insurance.premium_payments WHERE customer_id = 'CUST789' AND status = 'Completed' AND payment_date BETWEEN '2023-01-01' AND '2023-12-31';

[User] Okay, instead of all columns, just show the policy ID, payment date, and amount paid, ordered by payment date descending.

[Assistant] SELECT policy_id, payment_date, amount_paid FROM insurance.premium_payments WHERE customer_id = 'CUST789' AND status = 'Completed' AND payment_date BETWEEN '2023-01-01' AND '2023-12-31' ORDER BY payment_date DESC;


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

[User] Find all applications that were submitted in 2023 but received a decision ('Approved' or 'Rejected') in 2024. List the application ID, submitted date, decision date, and status.

[Assistant] SELECT application_id, submitted_at, decision_date, status FROM government_services.applications WHERE submitted_at BETWEEN '2023-01-01 00:00:00' AND '2023-12-31 23:59:59' AND status IN ('Approved', 'Rejected') AND decision_date BETWEEN '2024-01-01' AND '2024-12-31';


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE insurance.policy_beneficiaries ( beneficiary_id text, policy_id text, customer_id text, first_name text, last_name text, relationship text, percentage_share numeric, contact_info text, added_at timestamp )

[User] Show me all policy beneficiaries who were added in the last 6 months, along with their full names and relationship to the policyholder.

[Assistant] SELECT beneficiary_id, policy_id, first_name, last_name, relationship, percentage_share FROM insurance.policy_beneficiaries WHERE added_at >= NOW() - INTERVAL '6 months';

[User] Now filter these results to only show beneficiaries who have a percentage share greater than 30% and include their contact information.

[Assistant] SELECT beneficiary_id, policy_id, first_name, last_name, relationship, percentage_share, contact_info FROM insurance.policy_beneficiaries WHERE added_at >= NOW() - INTERVAL '6 months' AND percentage_share > 30;

[User] I also want to see the customer_id for these policies and filter to only show beneficiaries who are listed as 'spouse' or 'child'.

[Assistant] SELECT beneficiary_id, policy_id, customer_id, first_name, last_name, relationship, percentage_share, contact_info FROM insurance.policy_beneficiaries WHERE added_at >= NOW() - INTERVAL '6 months' AND percentage_share > 30 AND relationship IN ('spouse', 'child');

[User] Finally, show me the count of such beneficiaries per policy_id.

[Assistant] SELECT policy_id, COUNT(*) AS beneficiary_count FROM insurance.policy_beneficiaries WHERE added_at >= NOW() - INTERVAL '6 months' AND percentage_share > 30 AND relationship IN ('spouse', 'child') GROUP BY policy_id;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE legal_services.law_firms ( firm_id.text, firm_name.text, address.text, phone.text, website.text, founded_date.date, managing_partner_id.text )

[User] List all law firms that do not have a website registered, including their firm name and phone.

[Assistant]
SELECT firm_name, phone
FROM legal_services.law_firms
WHERE website IS NULL OR website = '';


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE gaming_technology.players ( player_id uuid, username text, email text, password_hash text, registration_date timestamp with time zone, last_login timestamp with time zone, country_code text, status text, profile_data jsonb )
CREATE TABLE gaming_technology.games ( game_id uuid, title text, developer_id uuid, publisher_id uuid, genre text, release_date date, description text, platform text, engine text, website text )
CREATE TABLE gaming_technology.developers ( developer_id uuid, name text, country text, founded_year integer, website text, created_at timestamp with time zone )
CREATE TABLE gaming_technology.servers ( server_id uuid, game_id uuid, server_name text, region text, ip_address text, port integer, current_players integer, max_players integer, status text, last_heartbeat timestamp with time zone )
CREATE TABLE gaming_technology.achievements ( achievement_id uuid, game_id uuid, name text, description text, icon_url text, points integer, hidden boolean )
CREATE TABLE gaming_technology.player_achievements ( player_achievement_id uuid, player_id uuid, achievement_id uuid, unlocked_at timestamp with time zone )

[User] List all game titles and corresponding server names for servers that are located in the same region as 'us-central-1'.

[Assistant]
SELECT g.title, s.server_name
FROM gaming_technology.servers s
JOIN gaming_technology.games g ON s.game_id = g.game_id
WHERE s.region = 'us-central-1';

[User] Additionally, include the username of every player who has had a session on each of those servers.

[Assistant]
SELECT g.title, s.server_name, p.username
FROM gaming_technology.servers s
JOIN gaming_technology.games g ON s.game_id = g.game_id
JOIN gaming_technology.game_sessions gs ON gs.server_id = s.server_id
JOIN gaming_technology.players p ON gs.player_id = p.player_id
WHERE s.region = 'us-central-1';


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE 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.services ( service_id.text, agency_id.text, service_name.text, description.text, category.text, eligibility_criteria.text, standard_fee.numeric, average_processing_time_days.integer, is_active.boolean, online_application_url.text )
CREATE TABLE government_services.applications ( application_id.text, citizen_id.text, service_id.text, submitted_at.timestamp, status.text, last_updated_at.timestamp, assigned_employee_id.text, decision_date.date, notes.text, reference_number.text )
CREATE TABLE government_services.documents ( document_id.text, application_id.text, citizen_id.text, document_type.text, file_reference.text, upload_timestamp.timestamp, expiry_date.date, verification_status.text, verified_by_employee_id.text, verification_timestamp.timestamp )
CREATE TABLE government_services.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 )
CREATE TABLE government_services.appointments ( appointment_id.text, citizen_id.text, employee_id.text, location_id.text, service_id.text, scheduled_start_time.timestamp, scheduled_end_time.timestamp, purpose.text, status.text, booking_method.text, created_at.timestamp, notes.text )

[User] Show each employee's first and last name along with the number of appointments they have scheduled in March 2024.

[Assistant]
SELECT e.first_name, e.last_name, COUNT(ap.appointment_id) AS appointment_count
FROM government_services.employees e
LEFT JOIN government_services.appointments ap ON e.employee_id = ap.employee_id
WHERE ap.scheduled_start_time >= '2024-03-01'
  AND ap.scheduled_start_time < '2024-04-01'
GROUP BY e.first_name, e.last_name;

[User] Only include appointments that are currently in the 'Scheduled' status.

[Assistant]
SELECT e.first_name, e.last_name, COUNT(ap.appointment_id) AS appointment_count
FROM government_services.employees e
LEFT JOIN government_services.appointments ap ON e.employee_id = ap.employee_id
WHERE ap.scheduled_start_time >= '2024-03-01'
  AND ap.scheduled_start_time < '2024-04-01'
  AND ap.status = 'Scheduled'
GROUP BY e.first_name, e.last_name;

[User] Also include the location name for where those appointments are scheduled.

[Assistant]
SELECT e.first_name, e.last_name, sl.location_name, COUNT(ap.appointment_id) AS appointment_count
FROM government_services.employees e
LEFT JOIN government_services.appointments ap ON e.employee_id = ap.employee_id
LEFT JOIN government_services.service_locations sl ON ap.location_id = sl.location_id
WHERE ap.scheduled_start_time >= '2024-03-01'
  AND ap.scheduled_start_time < '2024-04-01'
  AND ap.status = 'Scheduled'
GROUP BY e.first_name, e.last_name, sl.location_name;

[User] Sort the result by appointment_count in descending order and limit to the top 5 employees.

[Assistant]
SELECT e.first_name, e.last_name, sl.location_name, COUNT(ap.appointment_id) AS appointment_count
FROM government_services.employees e
LEFT JOIN government_services.appointments ap ON e.employee_id = ap.employee_id
LEFT JOIN government_services.service_locations sl ON ap.location_id = sl.location_id
WHERE ap.scheduled_start_time >= '2024-03-01'
  AND ap.scheduled_start_time < '2024-04-01'
  AND ap.status = 'Scheduled'
GROUP BY e.first_name, e.last_name, sl.location_name
ORDER BY appointment_count DESC
LIMIT 5;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE 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.prescriptions ( prescription_id.text, record_id.text, patient_id.text, doctor_id.text, medication_id.text, dosage.text, frequency.text, route.text, start_date.date, end_date.date, quantity_dispensed.numeric, refills_allowed.integer, prescription_date.timestamp )
CREATE TABLE healthcare.patient_insurance ( patient_insurance_id character varying(64) NOT NULL, patient_id character varying(64) NOT NULL, plan_id character varying(64) NOT NULL, policy_number character varying(100) NOT NULL, group_number character varying(100), subscriber_name character varying(200), effective_date date NOT NULL, expiration_date date, is_primary boolean NOT NULL DEFAULT true, PRIMARY KEY (patient_insurance_id), UNIQUE (patient_id, plan_id, policy_number) )

[User] Find appointments and prescriptions associated with the same patient and doctor. Show the appointment ID, prescription ID, patient ID, and doctor ID.

[Assistant] SELECT T1.appointment_id ,  T2.prescription_id ,  T1.patient_id ,  T1.doctor_id FROM healthcare.appointments AS T1 JOIN healthcare.prescriptions AS T2 ON T1.patient_id  =  T2.patient_id AND T1.doctor_id  =  T2.doctor_id

[User] Refine the list to only include cases where the prescription start date is before the appointment time. Add the start date and appointment time to the results.

[Assistant] SELECT T1.appointment_id ,  T2.prescription_id ,  T1.patient_id ,  T1.doctor_id ,  T2.start_date ,  T1.appointment_time FROM healthcare.appointments AS T1 JOIN healthcare.prescriptions AS T2 ON T1.patient_id  =  T2.patient_id AND T1.doctor_id  =  T2.doctor_id WHERE T2.start_date  <  DATE(T1.appointment_time)


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE token_basic_info ( coin_id.text, token_name.text, token_symbol.text, token_address.text, chain.text, price.numeric, price_change_percentage_1h.numeric, price_change_percentage_24h.numeric, price_change_percentage_7d.numeric, highest_price_24h.numeric, lowest_price_24h.numeric, market_cap.numeric, market_cap_rank.numeric, market_cap_change_percentage_24h.text, total_volume.text, narrative.text, trend_rank.numeric )

[User] List the top 5 tokens by price_change_percentage_7d, showing token_symbol, narrative, and price_change_percentage_7d.

[Assistant]
SELECT token_symbol, narrative, price_change_percentage_7d
FROM token_basic_info
ORDER BY price_change_percentage_7d DESC
LIMIT 5;


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

[User] List pairs of securities that belong to the same sector but have different currencies.

[Assistant] SELECT a.sector, a.ticker_symbol AS symbol_a, a.currency AS currency_a, b.ticker_symbol AS symbol_b, b.currency AS currency_b FROM financial_services.securities a JOIN financial_services.securities b ON a.sector = b.sector AND a.currency <> b.currency;

[User] Filter the pairs to only include sector = 'Healthcare'.

[Assistant] SELECT a.sector, a.ticker_symbol AS symbol_a, a.currency AS currency_a, b.ticker_symbol AS symbol_b, b.currency AS currency_b FROM financial_services.securities a JOIN financial_services.securities b ON a.sector = b.sector AND a.currency <> b.currency WHERE a.sector = 'Healthcare';

[User] Ensure uniqueness by only showing symbol_a < symbol_b.

[Assistant] SELECT a.sector, a.ticker_symbol AS symbol_a, a.currency AS currency_a, b.ticker_symbol AS symbol_b, b.currency AS currency_b FROM financial_services.securities a JOIN financial_services.securities b ON a.sector = b.sector AND a.currency <> b.currency AND a.ticker_symbol < b.ticker_symbol WHERE a.sector = 'Healthcare';


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE gaming_technology.players ( player_id uuid NOT NULL DEFAULT gen_random_uuid(), username character varying(100) NOT NULL UNIQUE, email character varying(255) NOT NULL UNIQUE, password_hash text NOT NULL, registration_date timestamp with time zone NOT NULL DEFAULT CURRENT_TIMESTAMP, last_login timestamp with time zone, country_code character(2), status character varying(20) NOT NULL DEFAULT 'active', profile_data jsonb, PRIMARY KEY (player_id) )
CREATE TABLE gaming_technology.games ( game_id uuid NOT NULL DEFAULT gen_random_uuid(), title character varying(200) NOT NULL, developer_id uuid NOT NULL, publisher_id uuid, genre character varying(100), release_date date, description text, platform character varying(50) NOT NULL, engine character varying(100), website character varying(255), PRIMARY KEY (game_id) )
CREATE TABLE gaming_technology.player_achievements ( player_achievement_id uuid NOT NULL DEFAULT gen_random_uuid(), player_id uuid NOT NULL, achievement_id uuid NOT NULL, unlocked_at timestamp with time zone NOT NULL DEFAULT CURRENT_TIMESTAMP, PRIMARY KEY (player_achievement_id), UNIQUE (player_id, achievement_id) )

[User] Retrieve the title and release_date of all games on the 'PC' platform.

[Assistant]
SELECT title, release_date
FROM gaming_technology.games
WHERE platform = 'PC';

[User] Now exclude any games released before 2018.

[Assistant]
SELECT title, release_date
FROM gaming_technology.games
WHERE platform = 'PC'
  AND release_date >= '2018-01-01';

[User] Also sort the results by release_date in ascending order.

[Assistant]
SELECT title, release_date
FROM gaming_technology.games
WHERE platform = 'PC'
  AND release_date >= '2018-01-01'
ORDER BY release_date ASC;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE government_services.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] How many service locations are there for each agency? List the agency ID and the count of locations.

[Assistant] SELECT agency_id ,  count(*) FROM government_services.service_locations GROUP BY 1


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE legal_services.cases ( case_id.text, case_number.text, case_name.text, client_id.text, lead_lawyer_id.text, case_type.text, status.text, date_opened.timestamp, date_closed.timestamp, description.text, court_jurisdiction.text )
CREATE TABLE legal_services.time_entries (
    entry_id 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.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] Show me all time entries, including the case name they are associated with.

[Assistant] SELECT T1.*, T2.case_name FROM time_entries AS T1 JOIN cases AS T2 ON T1.case_id = T2.case_id

[User] Only show me time entries for lawyer with ID 'lawyer_789'.

[Assistant] SELECT T1.*, T2.case_name FROM time_entries AS T1 JOIN cases AS T2 ON T1.case_id = T2.case_id WHERE T1.lawyer_id = 'lawyer_789'

[User] Actually, I only want entries for the date '2024-07-30', and just show the entry description, hours spent, and case name.

[Assistant] SELECT T1.description, T1.hours_spent, T2.case_name FROM time_entries AS T1 JOIN cases AS T2 ON T1.case_id = T2.case_id WHERE T1.lawyer_id = 'lawyer_789' AND T1.date_worked = '2024-07-30'


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE web3.token_transfers ( transfer_id text, token_id text, from_address text, to_address text, value numeric, transaction_id text, log_index integer )

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

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

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

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


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE healthcare.patients ( patient_id text, first_name text, last_name text, date_of_birth date, gender text, address text, phone_number text, email text, emergency_contact_name text, emergency_contact_phone text, created_at timestamp, updated_at timestamp )
CREATE TABLE healthcare.appointments ( appointment_id text, patient_id text, doctor_id text, appointment_time timestamp, duration_minutes integer, reason text, status text, location_id text, notes text, created_at timestamp )
CREATE TABLE healthcare.diagnoses ( diagnosis_id text, record_id text, patient_id text, doctor_id text, diagnosis_code text, code_type text, description text, diagnosis_date date, status text, is_chronic boolean )
CREATE TABLE healthcare.medications ( medication_id text, medication_name text, generic_name text, manufacturer text, ndc_code text, description text )

[User] Show me the full names of all patients who have received a diagnosis for 'hypertension', along with the appointment time and the doctor's full name for each related appointment.

[Assistant]
SELECT p.first_name, p.last_name, a.appointment_time, d2.first_name AS doctor_first_name, d2.last_name AS doctor_last_name
FROM healthcare.diagnoses diag
JOIN healthcare.patients p ON diag.patient_id = p.patient_id
JOIN healthcare.appointments a ON diag.patient_id = a.patient_id AND diag.doctor_id = a.doctor_id
JOIN healthcare.patients d2 ON diag.doctor_id = d2.patient_id
WHERE diag.diagnosis_code = 'hypertension';

[User] Actually, can you update the query to only include those appointments that are currently marked as 'scheduled'?

[Assistant]
SELECT p.first_name, p.last_name, a.appointment_time, d2.first_name AS doctor_first_name, d2.last_name AS doctor_last_name
FROM healthcare.diagnoses diag
JOIN healthcare.patients p ON diag.patient_id = p.patient_id
JOIN healthcare.appointments a ON diag.patient_id = a.patient_id AND diag.doctor_id = a.doctor_id
JOIN healthcare.patients d2 ON diag.doctor_id = d2.patient_id
WHERE diag.diagnosis_code = 'hypertension' AND a.status = 'scheduled';

[User] I got an error: doctor information seems to be incorrect, since doctors shouldn’t be retrieved from the patients table. Can you fix the join so the doctor information comes from the correct table?

[Assistant]
SELECT p.first_name, p.last_name, a.appointment_time, doc.first_name AS doctor_first_name, doc.last_name AS doctor_last_name
FROM healthcare.diagnoses diag
JOIN healthcare.patients p ON diag.patient_id = p.patient_id
JOIN healthcare.appointments a ON diag.patient_id = a.patient_id AND diag.doctor_id = a.doctor_id
JOIN healthcare.doctors doc ON diag.doctor_id = doc.doctor_id
WHERE diag.diagnosis_code = 'hypertension' AND a.status = 'scheduled';


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE web3.tokens (
    token_id character varying(64) NOT NULL,  -- unique identifier for the token
    contract_address character varying(128) NOT NULL, -- address of the token contract
    token_name character varying(128) NOT NULL, -- name of the token
    token_symbol character varying(32) NOT NULL, -- symbol of the token
    decimals integer NOT NULL, -- number of decimals for the token
    total_supply numeric(38,14) NOT NULL, -- total supply of the token
    PRIMARY KEY (token_id)
)

[User] List all tokens with a total supply greater than 1,000,000.

[Assistant]
SELECT token_id, token_name, token_symbol, contract_address, total_supply
FROM web3.tokens
WHERE total_supply > 1000000;

[User] Can you also include the decimals for each token in the result?

[Assistant]
SELECT token_id, token_name, token_symbol, contract_address, total_supply, decimals
FROM web3.tokens
WHERE total_supply > 1000000;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE transportation.vehicles ( vehicle_id character varying(64) NOT NULL, license_plate character varying(32) NOT NULL UNIQUE, vin character varying(17) UNIQUE, make character varying(64) NOT NULL, model character varying(64) NOT NULL, year integer NOT NULL, type character varying(32) NOT NULL, capacity integer, fuel_type character varying(32) NOT NULL, status character varying(32) NOT NULL, depot_id character varying(64), acquisition_date date, PRIMARY KEY (vehicle_id) )
CREATE TABLE transportation.trips ( trip_id character varying(64) NOT NULL, route_id character varying(64), vehicle_id character varying(64) NOT NULL, driver_id character varying(64) NOT NULL, scheduled_departure timestamp with time zone NOT NULL, actual_departure timestamp with time zone, scheduled_arrival timestamp with time zone NOT NULL, actual_arrival timestamp with time zone, origin_location_id character varying(64) NOT NULL, destination_location_id character varying(64) NOT NULL, status character varying(32) NOT NULL, passenger_count integer, cargo_manifest_id character varying(64), PRIMARY KEY (trip_id) )
CREATE TABLE transportation.locations ( location_id character varying(64) NOT NULL, name character varying(255) NOT NULL, type character varying(64) NOT NULL, address_line1 character varying(255), city character varying(128), state_province character varying(128), postal_code character varying(32), country character varying(64) NOT NULL, latitude numeric(9, 6), longitude numeric(9, 6), timezone character varying(64), PRIMARY KEY (location_id) )
CREATE TABLE transportation.maintenance_logs ( log_id character varying(64) NOT NULL, vehicle_id character varying(64) NOT NULL, service_date date NOT NULL, odometer_reading integer, service_type character varying(128) NOT NULL, description text NOT NULL, cost numeric(10, 2), mechanic_name character varying(128), next_service_due_date date, PRIMARY KEY (log_id) )
CREATE TABLE transportation.fuel_logs ( fuel_log_id character varying(64) NOT NULL, vehicle_id character varying(64) NOT NULL, trip_id character varying(64), log_timestamp timestamp with time zone NOT NULL, fuel_type character varying(32) NOT NULL, quantity numeric(10, 3) NOT NULL, unit character varying(16) NOT NULL, cost_per_unit numeric(8, 4), total_cost numeric(10, 2) NOT NULL, odometer_reading integer, location_id character varying(64), PRIMARY KEY (fuel_log_id) )
CREATE TABLE transportation.passengers ( passenger_id character varying(64) NOT NULL, first_name character varying(128) NOT NULL, last_name character varying(128) NOT NULL, email character varying(128) UNIQUE, phone_number character varying(32) UNIQUE, date_of_birth date, loyalty_program_id character varying(64), created_at timestamp with time zone NOT NULL, PRIMARY KEY (passenger_id) )

[User] Which vehicles have a total maintenance cost exceeding 10000 across all their maintenance logs?

[Assistant] SELECT vehicle_id, SUM(cost) AS total_maintenance_cost FROM transportation.maintenance_logs GROUP BY vehicle_id HAVING SUM(cost) > 10000;

[User] For these vehicles, also show the count of maintenance logs and the average cost per log.

[Assistant] SELECT vehicle_id, COUNT(log_id) AS maintenance_log_count, AVG(cost) AS average_maintenance_cost FROM transportation.maintenance_logs GROUP BY vehicle_id HAVING SUM(cost) > 10000;