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.employees (
    employee_id character varying(64) NOT NULL,  -- unique identifier for the employee
    first_name character varying(100) NOT NULL,
    last_name character varying(100) NOT NULL,
    job_title character varying(100) NOT NULL, -- e.g., Teller, Branch Manager, Financial Advisor, Analyst
    department character varying(100), -- e.g., Retail Banking, Wealth Management, IT
    branch_id character varying(64), -- Identifier for the branch they work at (if applicable)
    email character varying(128) NOT NULL UNIQUE,
    phone_extension character varying(20),
    hire_date date NOT NULL,
    termination_date date, -- Date of termination, null if currently employed
    manager_id character varying(64), -- Self-referencing key for manager relationship
    status character varying(32) NOT NULL, -- e.g., Active, Terminated, On Leave
    PRIMARY KEY (employee_id),
    FOREIGN KEY (branch_id) REFERENCES financial_services.branches(branch_id), -- Assuming a branches table exists
    FOREIGN KEY (manager_id) REFERENCES financial_services.employees(employee_id)
)

[User] How many employees are there in each department grouped by their status?

[Assistant]
SELECT department,
       status,
       COUNT(*) AS employee_count
FROM financial_services.employees
GROUP BY department, status;

[User] Exclude any groups where the employee count is less than 5.

[Assistant]
SELECT department,
       status,
       COUNT(*) AS employee_count
FROM financial_services.employees
GROUP BY department, status
HAVING COUNT(*) >= 5;

[User] Finally, order the results by department name descending.

[Assistant]
SELECT department,
       status,
       COUNT(*) AS employee_count
FROM financial_services.employees
GROUP BY department, status
HAVING COUNT(*) >= 5
ORDER BY department 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.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 )

[User] List all employees whose job titles differ from their direct managers. Provide each employee's full name, their job title, the manager's full name, and the manager's job title.

[Assistant] SELECT e.first_name || ' ' || e.last_name AS employee_name, e.job_title AS employee_job_title, m.first_name || ' ' || m.last_name AS manager_name, m.job_title AS manager_job_title FROM government_services.employees e JOIN government_services.employees m ON e.manager_employee_id = m.employee_id WHERE e.job_title <> m.job_title;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE insurance.policies ( policy_id text, 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.premium_payments ( payment_id text, policy_id text, customer_id text, payment_date timestamp, amount_paid numeric, payment_method text, transaction_reference text, due_date date, payment_period_start date, payment_period_end date, status text )
CREATE TABLE insurance.claim_documents ( document_id text, claim_id text, document_type text, file_name text, file_path text, file_size_bytes integer, mime_type text, uploaded_by text, uploaded_at timestamp, description text )
CREATE TABLE insurance.policy_beneficiaries ( beneficiary_id text, policy_id text, customer_id text, first_name text, last_name text, relationship text, percentage_share numeric, contact_info text, added_at timestamp )

[User] For each policy, list the policy number and the total amount paid in premium payments.

[Assistant]
SELECT p.policy_number, SUM(pay.amount_paid) AS total_paid
FROM insurance.policies p
JOIN insurance.premium_payments pay ON p.policy_id = pay.policy_id
GROUP BY p.policy_number;

[User] Only include policies where the total paid is less than 2000.

[Assistant]
SELECT p.policy_number, SUM(pay.amount_paid) AS total_paid
FROM insurance.policies p
JOIN insurance.premium_payments pay ON p.policy_id = pay.policy_id
GROUP BY p.policy_number
HAVING SUM(pay.amount_paid) < 2000;


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,  -- unique identifier for the user
    username character varying(128) NOT NULL, -- username of the user
    email character varying(128) NOT NULL, -- email address of the user
    password_hash text NOT NULL, -- hashed password of the user
    created_at timestamp NOT NULL, -- time when the user account was created
    PRIMARY KEY (user_id)
)
CREATE TABLE trading_platform.orders (
    order_id character varying(64) NOT NULL,  -- unique identifier for the order
    user_id character varying(64) NOT NULL, -- identifier of the user placing the order
    wallet_id character varying(64) NOT NULL, -- identifier of the wallet used for the order
    asset_id character varying(64) NOT NULL, -- identifier of the asset being traded
    order_type character varying(32) NOT NULL, -- type of the order (e.g., buy, sell)
    quantity numeric(38,14) NOT NULL, -- quantity of the asset in the order
    price numeric(38,14) NOT NULL, -- price per unit of the asset
    status character varying(32) NOT NULL, -- status of the order (e.g., open, filled, canceled)
    created_at timestamp NOT NULL, -- time when the order was created
    PRIMARY KEY (order_id)
)
CREATE TABLE trading_platform.dapps (
    dapp_id character varying(64) NOT NULL,  -- unique identifier for the DApp
    name character varying(128) NOT NULL, -- name of the DApp
    description text NOT NULL, -- description of the DApp
    url character varying(256) NOT NULL, -- URL of the DApp
    PRIMARY KEY (dapp_id)
)
CREATE TABLE trading_platform.peers (
    peer_id character varying(64) NOT NULL,  -- unique identifier for the peer
    ip_address character varying(15) NOT NULL, -- IP address of the peer
    port integer NOT NULL, -- port number of the peer
    last_seen timestamp NOT NULL, -- last time the peer was active
    PRIMARY KEY (peer_id)
)
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.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)
)

[User] For each asset, I want to know how many orders have the status 'filled', showing the asset symbol.

[Assistant]
SELECT m.value AS asset_symbol,
       COUNT(*) AS filled_order_count
FROM trading_platform.orders o
JOIN trading_platform.metadata m
  ON o.asset_id = m.asset_id
 AND m.key = 'symbol'
WHERE o.status = 'filled'
GROUP BY m.value;

[User] Include assets that have zero filled orders, showing filled_order_count as 0.

[Assistant]
WITH asset_symbols AS (
  SELECT DISTINCT asset_id,
         value AS asset_symbol
  FROM trading_platform.metadata
  WHERE key = 'symbol'
)
SELECT a.asset_symbol,
       COALESCE(f.filled_order_count, 0) AS filled_order_count
FROM asset_symbols a
LEFT JOIN (
  SELECT asset_id,
         COUNT(*) AS filled_order_count
  FROM trading_platform.orders
  WHERE status = 'filled'
  GROUP BY asset_id
) f
  ON a.asset_id = f.asset_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 financial_services.market_data (
    data_point_id bigserial NOT NULL, -- auto-incrementing primary key
    security_id character varying(64) NOT NULL, -- identifier for the security
    data_timestamp timestamp NOT NULL, -- timestamp for the data point (e.g., end of day, intraday)
    open_price numeric(19, 8), -- opening price for the period
    high_price numeric(19, 8), -- highest price during the period
    low_price numeric(19, 8), -- lowest price during the period
    close_price numeric(19, 8) NOT NULL, -- closing price for the period
    adjusted_close_price numeric(19, 8), -- closing price adjusted for dividends and splits
    volume bigint, -- trading volume during the period
    source character varying(50), -- source of the market data (e.g., Bloomberg, Refinitiv)
    PRIMARY KEY (data_point_id),
    UNIQUE (security_id, data_timestamp), -- Ensure unique data point per security per time
    FOREIGN KEY (security_id) REFERENCES financial_services.securities(security_id)
)

[User] List the ticker symbol and security name for all securities that had a volume greater than 100000 on '2023-10-27'.

[Assistant] SELECT T2.ticker_symbol, T2.security_name FROM financial_services.market_data AS T1 JOIN financial_services.securities AS T2 ON T1.security_id = T2.security_id WHERE T1.data_timestamp::date = '2023-10-27' AND T1.volume > 100000;

[User] Also include the close price from that day in the result.

[Assistant] SELECT T2.ticker_symbol, T2.security_name, T1.close_price FROM financial_services.market_data AS T1 JOIN financial_services.securities AS T2 ON T1.security_id = T2.security_id WHERE T1.data_timestamp::date = '2023-10-27' AND T1.volume > 100000;

[User] Filter this list to only show securities belonging to the 'Technology' sector.

[Assistant] SELECT T2.ticker_symbol, T2.security_name, T1.close_price FROM financial_services.market_data AS T1 JOIN financial_services.securities AS T2 ON T1.security_id = T2.security_id WHERE T1.data_timestamp::date = '2023-10-27' AND T1.volume > 100000 AND T2.sector = 'Technology';


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.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.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.player_inventory ( inventory_id uuid, player_id uuid, item_id uuid, quantity integer, acquired_at timestamp with time zone, instance_data jsonb )

[User] For each game and month, I'd like to see how many sessions started, showing game_id, title, and start_month.

[Assistant]
SELECT g.game_id,
       g.title,
       DATE_TRUNC('month', gs.start_time) AS start_month,
       COUNT(gs.session_id) AS session_count
FROM gaming_technology.games g
JOIN gaming_technology.game_sessions gs ON g.game_id = gs.game_id
GROUP BY g.game_id, g.title, DATE_TRUNC('month', gs.start_time);

[User] Can you filter to only include months where the session_count is greater than 100 and also add the average session duration?

[Assistant]
SELECT g.game_id,
       g.title,
       DATE_TRUNC('month', gs.start_time) AS start_month,
       COUNT(gs.session_id) AS session_count,
       AVG(gs.duration_seconds) AS avg_duration
FROM gaming_technology.games g
JOIN gaming_technology.game_sessions gs ON g.game_id = gs.game_id
GROUP BY g.game_id, g.title, DATE_TRUNC('month', gs.start_time)
HAVING COUNT(gs.session_id) > 100;


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.claims ( claim_id text PRIMARY KEY, policy_id text, customer_id text, incident_date timestamp, reported_date timestamp, description text, estimated_loss numeric, status text, settlement_amount numeric, settlement_date date, claim_handler_id text, police_report_number text )
CREATE TABLE insurance.insurance_products ( product_id text PRIMARY KEY, product_name text, product_type text, description text, base_premium numeric, coverage_details text, underwriting_rules text, is_active boolean, created_at timestamp, updated_at timestamp )
CREATE TABLE insurance.agents ( agent_id text PRIMARY KEY, first_name text, last_name text, agency_name text, license_number text, license_state text, contact_email text, contact_phone text, hire_date date, termination_date date, status text, commission_rate numeric, manager_id text )

[User] Show me the product name, product type, and the first and last name of all agents who have sold policies of each insurance product.

[Assistant]
SELECT ip.product_name, ip.product_type, a.first_name, a.last_name
FROM insurance.policies p
JOIN insurance.insurance_products ip ON p.product_id = ip.product_id
JOIN insurance.agents a ON p.agent_id = a.agent_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 erc1155_approval_for_all ( block_number bigint, block_timestamp timestamp, transaction_index integer, transaction_hash text, log_index integer, contract_address text )
CREATE TABLE erc20_balances_historical ( block_number bigint, contract_address text, wallet_address text, amount text, pk integer )
CREATE TABLE nft_holders ( block_number bigint, contract_address text, wallet_address text, token_id text, contract_type text, amount text, pk text )
CREATE TABLE nft_holder_historical ( block_number bigint, contract_address text, wallet_address text, token_id text, contract_type text, amount text, pk integer )
CREATE TABLE sui_coins_metadata ( object_id text, coin_type text, status text, decimals bigint, description text, icon_url text, symbol text, name text )
CREATE TABLE sui_nfts ( object_id text, status text, collection_type text, package_id text, previous_transaction text, display text, owner text, name text )
CREATE TABLE nft_metadata ( blockchain text, contract_address text, token_id text, contract_name text, erc_type text, amount bigint, minter text, owner text, mint_block_number bigint, mint_time bigint, mint_transaction_hash text, mint_price text, token_uri text, metadata text, name text, image_uri text, traits text, updated_at bigint, status text, rarity_score real, rarity_rank integer, unique_attribute_count integer, pk integer )
CREATE TABLE token_prices ( uuid text, blockchain text, address text, decimals bigint, symbol text, price real, timestamp timestamp )
CREATE TABLE token_prices_latest ( blockchain text, address text, decimals bigint, symbol text, price real, timestamp timestamp )
CREATE TABLE erc20_approval ( block_number bigint, block_timestamp timestamp, transaction_index integer, transaction_hash text, log_index integer, contract_address text, pk integer )
CREATE TABLE token_balances ( block_number bigint, block_timestamp timestamp, tick text, wallet_address text, total_supply decimal, amount decimal )
CREATE TABLE token_info ( block_timestamp timestamp, block_number bigint, tx_index integer, tx_hash text, tick text, max_supply decimal, lim decimal, wlim decimal, dec integer, creator text )
CREATE TABLE token_activities ( block_timestamp timestamp, block_number bigint, tx_index integer, tx_hash text, log_index integer, type text, tick text, id text, amt decimal, from_address text, to_address text )
CREATE TABLE mud_holesky_redstone ( address text, table_id text, key_bytes text, key0 text, key1 text, static_data text, encoded_lengths text, dynamic_data text, is_deleted boolean, block_number bigint, log_index bigint )
CREATE TABLE token_balances_bitcoin ( block_number bigint, block_timestamp timestamp, tick text, wallet_address text, total_supply text, amount text )
CREATE TABLE token_activities_bitcoin ( block_timestamp timestamp, block_number bigint, tx_index integer, tx_hash text, log_index integer, type text, tick text, id text, amt decimal, from_address text, to_address text )
CREATE TABLE token_balances_avalanche ( block_number bigint, 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] How many total records are there in the `erc20_approval` table?

[Assistant] SELECT COUNT(*) FROM erc20_approval

[User] And how many records are in the `erc1155_approval_for_all` table?

[Assistant] SELECT COUNT(*) FROM erc1155_approval_for_all

[User] List all unique wallet addresses that are present in the `nft_holders` table.

[Assistant] SELECT DISTINCT wallet_address FROM nft_holders

[User] How many unique wallet addresses have ever held an ERC20 token according to the `erc20_balances_historical` table?

[Assistant] SELECT COUNT(DISTINCT wallet_address) FROM erc20_balances_historical


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.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.service_locations (
    location_id character varying(64) NOT NULL, -- unique identifier for the physical location
    agency_id character varying(64) NOT NULL, -- FK to agencies table
    location_name character varying(200), -- e.g., Downtown DMV Office
    address text NOT NULL,
    city character varying(100),
    state character varying(50),
    postal_code character varying(20),
    latitude numeric(9, 6),
    longitude numeric(9, 6),
    operating_hours text, -- description of opening times
    contact_phone character varying(32),
    is_accessible boolean, -- accessibility information (e.g., wheelchair access)
    PRIMARY KEY (location_id)
)

[User] Which service locations are not accessible and belong to agencies with a jurisdiction level of 'Local'? Show the location name and city.

[Assistant]
SELECT sl.location_name, sl.city
FROM government_services.service_locations sl
INNER JOIN government_services.agencies a ON sl.agency_id = a.agency_id
WHERE sl.is_accessible = FALSE
  AND a.jurisdiction_level = 'Local';


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 character varying(64) NOT NULL, firm_name character varying(200) NOT NULL, address text NOT NULL, phone character varying(32), website character varying(255), founded_date date, managing_partner_id character varying(64), PRIMARY KEY (firm_id) )
CREATE TABLE legal_services.cases ( case_id character varying(64) NOT NULL, case_number character varying(100) UNIQUE, case_name text NOT NULL, client_id character varying(64) NOT NULL, lead_lawyer_id character varying(64) NOT NULL, case_type character varying(100) NOT NULL, status character varying(50) NOT NULL, date_opened timestamp NOT NULL, date_closed timestamp, description text, court_jurisdiction character varying(128), PRIMARY KEY (case_id) )

[User] Show me all case numbers along with the firm_name of the law firm where the lead lawyer is the managing partner.

[Assistant]
SELECT c.case_number, l.firm_name
FROM legal_services.cases c
JOIN legal_services.law_firms l
  ON c.lead_lawyer_id = l.managing_partner_id;

[User] Now only include cases with status 'Closed' and show the date_closed as well.

[Assistant]
SELECT c.case_number, l.firm_name, c.date_closed
FROM legal_services.cases c
JOIN legal_services.law_firms l
  ON c.lead_lawyer_id = l.managing_partner_id
WHERE c.status = 'Closed';


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

[User] Show policy numbers, start dates, and the type of the insurance product for policies with a deductible greater than 500.

[Assistant] SELECT T1.policy_number, T1.start_date, T2.product_type FROM insurance.policies AS T1 JOIN insurance.insurance_products AS T2 ON T1.product_id = T2.product_id WHERE T1.deductible > 500;

[User] Could you also include the product name and only show results for policies that are currently 'active'?

[Assistant] SELECT T1.policy_number, T1.start_date, T2.product_type, T2.product_name FROM insurance.policies AS T1 JOIN insurance.insurance_products AS T2 ON T1.product_id = T2.product_id WHERE T1.deductible > 500 AND T1.status = 'active';


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.claim_documents ( document_id text PRIMARY KEY, claim_id text, document_type text, file_name text, file_path text, file_size_bytes int, mime_type text, uploaded_by text, uploaded_at timestamp, description text )

[User] Find claim IDs that have more than 5 documents of type 'PHOTO'.

[Assistant] SELECT claim_id FROM insurance.claim_documents WHERE document_type = 'PHOTO' GROUP BY claim_id HAVING COUNT(*) > 5;

[User] Can you filter those claims to only include documents uploaded after '2024-01-01'? Show the claim_id, document_id, file_name, and uploaded_at for those specific documents.

[Assistant] SELECT claim_id, document_id, file_name, uploaded_at FROM insurance.claim_documents WHERE uploaded_at > '2024-01-01' AND claim_id IN ( SELECT claim_id FROM insurance.claim_documents WHERE document_type = 'PHOTO' GROUP BY claim_id HAVING COUNT(*) > 5 );

[User] Great. Now, only show documents that also have a file size greater than 1MB.

[Assistant] SELECT claim_id, document_id, file_name, uploaded_at FROM insurance.claim_documents WHERE uploaded_at > '2024-01-01' AND file_size_bytes > 1048576 AND claim_id IN ( SELECT claim_id FROM insurance.claim_documents WHERE document_type = 'PHOTO' GROUP BY claim_id HAVING COUNT(*) > 5 );


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

[User] Show the first and last names, email, and phone number for all patients who were added to the system in the last 90 days along with their emergency contact name.

[Assistant] SELECT first_name, last_name, email, phone_number, emergency_contact_name FROM healthcare.patients WHERE created_at >= NOW() - INTERVAL '90 days';

[User] Actually, can you also include the emergency contact phone number in the results?

[Assistant] SELECT first_name, last_name, email, phone_number, emergency_contact_name, emergency_contact_phone FROM healthcare.patients WHERE created_at >= NOW() - INTERVAL '90 days';

[User] Now filter to only patients whose emergency_contact_phone is not null.

[Assistant] SELECT first_name, last_name, email, phone_number, emergency_contact_name, emergency_contact_phone FROM healthcare.patients WHERE created_at >= NOW() - INTERVAL '90 days' AND emergency_contact_phone IS NOT NULL;

[User] Sorry, I only want patients whose phone_number field is empty. Can you update the query?

[Assistant] SELECT first_name, last_name, email, phone_number, emergency_contact_name, emergency_contact_phone FROM healthcare.patients WHERE created_at >= NOW() - INTERVAL '90 days' AND emergency_contact_phone IS NOT NULL AND (phone_number IS NULL OR phone_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 social_media.users (
    user_id character varying(64) NOT NULL,  -- unique identifier for the user
    username character varying(50) NOT NULL UNIQUE, -- user's unique handle
    email character varying(128) NOT NULL UNIQUE, -- user's email address
    password_hash text NOT NULL, -- hashed password
    full_name character varying(100), -- user's full name
    profile_picture_url text, -- URL to the profile picture
    bio text, -- short user biography
    location character varying(100), -- user's location
    created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, -- timestamp of account creation
    updated_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, -- timestamp of last profile update
    is_verified boolean NOT NULL DEFAULT false, -- verification status
    PRIMARY KEY (user_id)
)
CREATE TABLE social_media.hashtags ( hashtag_id character varying(64) NOT NULL, tag_name character varying(100) NOT NULL UNIQUE, created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, PRIMARY KEY (hashtag_id) )
CREATE TABLE social_media.post_hashtags ( post_hashtag_id character varying(64) NOT NULL, post_id character varying(64) NOT NULL, hashtag_id character varying(64) NOT NULL, PRIMARY KEY (post_hashtag_id), CONSTRAINT unique_post_hashtag UNIQUE (post_id, hashtag_id) )
CREATE TABLE social_media.messages ( message_id character varying(64) NOT NULL, conversation_id character varying(64) NOT NULL, sender_user_id character varying(64) NOT NULL, content text, media_url text, media_type character varying(20), sent_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, read_at timestamp, PRIMARY KEY (message_id) )
CREATE TABLE social_media.conversations ( conversation_id text PRIMARY KEY, created_at timestamp, last_message_at timestamp, is_group_chat bool, group_name text )
CREATE TABLE social_media.notifications ( notification_id text PRIMARY KEY, recipient_user_id text, sender_user_id text, notification_type text, target_entity_id text, target_entity_type text, created_at timestamp, read_at timestamp )
CREATE TABLE social_media.user_settings ( setting_id text, user_id text, theme text, email_notifications_enabled boolean, push_notifications_enabled boolean, private_profile boolean, updated_at timestamp )

[User] I need to get the most recent message each verified user has sent in any group chat, showing username, group_name, message_id, and sent_at.

[Assistant]
WITH user_recent AS (
  SELECT m.sender_user_id, m.message_id, m.conversation_id, m.sent_at,
         ROW_NUMBER() OVER (PARTITION BY m.sender_user_id ORDER BY m.sent_at DESC) AS rn
  FROM social_media.messages m
  JOIN social_media.conversations c ON m.conversation_id = c.conversation_id
  WHERE c.is_group_chat = true
)
SELECT u.username, c.group_name, ur.message_id, ur.sent_at
FROM user_recent ur
JOIN social_media.users u ON ur.sender_user_id = u.user_id
JOIN social_media.conversations c ON ur.conversation_id = c.conversation_id
WHERE ur.rn = 1
  AND u.is_verified = true;

[User] Actually, I only want messages sent in the past 30 days.

[Assistant]
WITH user_recent AS (
  SELECT m.sender_user_id, m.message_id, m.conversation_id, m.sent_at,
         ROW_NUMBER() OVER (PARTITION BY m.sender_user_id ORDER BY m.sent_at DESC) AS rn
  FROM social_media.messages m
  JOIN social_media.conversations c ON m.conversation_id = c.conversation_id
  WHERE c.is_group_chat = true
    AND m.sent_at >= NOW() - INTERVAL '30 days'
)
SELECT u.username, c.group_name, ur.message_id, ur.sent_at
FROM user_recent ur
JOIN social_media.users u ON ur.sender_user_id = u.user_id
JOIN social_media.conversations c ON ur.conversation_id = c.conversation_id
WHERE ur.rn = 1
  AND u.is_verified = true;

[User] Also, exclude any users who have disabled push notifications.

[Assistant]
WITH user_recent AS (
  SELECT m.sender_user_id, m.message_id, m.conversation_id, m.sent_at,
         ROW_NUMBER() OVER (PARTITION BY m.sender_user_id ORDER BY m.sent_at DESC) AS rn
  FROM social_media.messages m
  JOIN social_media.conversations c ON m.conversation_id = c.conversation_id
  WHERE c.is_group_chat = true
    AND m.sent_at >= NOW() - INTERVAL '30 days'
)
SELECT u.username, c.group_name, ur.message_id, ur.sent_at
FROM user_recent ur
JOIN social_media.users u ON ur.sender_user_id = u.user_id
JOIN social_media.conversations c ON ur.conversation_id = c.conversation_id
JOIN social_media.user_settings s ON s.user_id = u.user_id
WHERE ur.rn = 1
  AND u.is_verified = true
  AND s.push_notifications_enabled = true;

[User] And order the results by sent_at descending.

[Assistant]
WITH user_recent AS (
  SELECT m.sender_user_id, m.message_id, m.conversation_id, m.sent_at,
         ROW_NUMBER() OVER (PARTITION BY m.sender_user_id ORDER BY m.sent_at DESC) AS rn
  FROM social_media.messages m
  JOIN social_media.conversations c ON m.conversation_id = c.conversation_id
  WHERE c.is_group_chat = true
    AND m.sent_at >= NOW() - INTERVAL '30 days'
)
SELECT u.username, c.group_name, ur.message_id, ur.sent_at
FROM user_recent ur
JOIN social_media.users u ON ur.sender_user_id = u.user_id
JOIN social_media.conversations c ON ur.conversation_id = c.conversation_id
JOIN social_media.user_settings s ON s.user_id = u.user_id
WHERE ur.rn = 1
  AND u.is_verified = true
  AND s.push_notifications_enabled = true
ORDER BY ur.sent_at DESC;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE insurance.customers ( customer_id character varying(64) NOT NULL, first_name character varying(100) NOT NULL, last_name character varying(100) NOT NULL, date_of_birth date NOT NULL, ssn_hash character varying(128), address_line1 character varying(255) NOT NULL, address_line2 character varying(255), city character varying(100) NOT NULL, state character varying(50) NOT NULL, zip_code character varying(20) NOT NULL, country character varying(50) NOT NULL DEFAULT 'USA', phone_number character varying(30), email character varying(128) UNIQUE, created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, updated_at timestamp, status character varying(20) NOT NULL DEFAULT 'Active', PRIMARY KEY (customer_id) )
CREATE TABLE insurance.policies ( policy_id character varying(64) NOT NULL, customer_id character varying(64) NOT NULL, product_id character varying(64) NOT NULL, agent_id character varying(64), policy_number character varying(100) NOT NULL UNIQUE, start_date date NOT NULL, end_date date NOT NULL, premium_amount numeric(12, 2) NOT NULL, coverage_limit numeric(15, 2) NOT NULL, deductible numeric(10, 2) NOT NULL, status character varying(30) NOT NULL, issued_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, cancellation_date date, cancellation_reason text, PRIMARY KEY (policy_id) )
CREATE TABLE insurance.claims ( claim_id character varying(64) NOT NULL, policy_id character varying(64) NOT NULL, customer_id character varying(64) NOT NULL, incident_date timestamp NOT NULL, reported_date timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, description text NOT NULL, estimated_loss numeric(15, 2), status character varying(30) NOT NULL, settlement_amount numeric(15, 2), settlement_date date, claim_handler_id character varying(64), police_report_number character varying(100), PRIMARY KEY (claim_id) )
CREATE TABLE insurance.insurance_products ( product_id character varying(64) NOT NULL, product_name character varying(150) NOT NULL, product_type character varying(50) NOT NULL, description text, base_premium numeric(10, 2) NOT NULL, coverage_details text, underwriting_rules text, is_active boolean NOT NULL DEFAULT true, created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, updated_at timestamp, PRIMARY KEY (product_id) )
CREATE TABLE insurance.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) )
CREATE TABLE insurance.claim_documents ( document_id character varying(64) NOT NULL, claim_id character varying(64) NOT NULL, document_type character varying(50) NOT NULL, file_name character varying(255) NOT NULL, file_path character varying(512) NOT NULL, file_size_bytes integer, mime_type character varying(100), uploaded_by character varying(64), uploaded_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, description text, PRIMARY KEY (document_id) )

[User] Show all claim documents (document_id, file_name, and document_type) for claims that have a settlement amount greater than 5000.

[Assistant]
SELECT cd.document_id, cd.file_name, cd.document_type
FROM insurance.claim_documents cd
JOIN insurance.claims c ON cd.claim_id = c.claim_id
WHERE c.settlement_amount > 5000;

[User] Can you also add the claim_id and only include documents with a file size over 1MB (1048576 bytes)?

[Assistant]
SELECT cd.document_id, cd.claim_id, cd.file_name, cd.document_type
FROM insurance.claim_documents cd
JOIN insurance.claims c ON cd.claim_id = c.claim_id
WHERE c.settlement_amount > 5000 AND cd.file_size_bytes > 1048576;

[User] Instead, just show the claim_id and how many such documents meet these requirements for each claim.

[Assistant]
SELECT cd.claim_id, COUNT(*) AS document_count
FROM insurance.claim_documents cd
JOIN insurance.claims c ON cd.claim_id = c.claim_id
WHERE c.settlement_amount > 5000 AND cd.file_size_bytes > 1048576
GROUP BY cd.claim_id;

[User] Now, please order the results by document_count descending and limit to the top 5 claims.

[Assistant]
SELECT cd.claim_id, COUNT(*) AS document_count
FROM insurance.claim_documents cd
JOIN insurance.claims c ON cd.claim_id = c.claim_id
WHERE c.settlement_amount > 5000 AND cd.file_size_bytes > 1048576
GROUP BY cd.claim_id
ORDER BY document_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 legal_services.invoices (
    invoice_id character varying(64) NOT NULL,  -- unique identifier for the invoice
    invoice_number character varying(100) UNIQUE NOT NULL, -- user-facing invoice number
    client_id character varying(64) NOT NULL, -- FK to clients table
    case_id character varying(64), -- FK to cases table (optional, could be general retainer)
    issue_date date NOT NULL, -- date the invoice was generated
    due_date date NOT NULL, -- date the payment is due
    total_amount numeric(12, 2) NOT NULL, -- total amount due on the invoice
    amount_paid numeric(12, 2) DEFAULT 0.00, -- amount already paid
    status character varying(50) NOT NULL, -- e.g., Draft, Sent, Paid, Partially Paid, Overdue, Void
    payment_date timestamp, -- date the invoice was fully paid (nullable)
    notes text, -- additional notes or terms on the invoice
    created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
    PRIMARY KEY (invoice_id)
)

[User] Can you list the invoice numbers, issue dates, and due dates for all invoices, sorted by issue date ascending?

[Assistant] SELECT invoice_number, issue_date, due_date FROM legal_services.invoices ORDER BY issue_date ASC;

[User] I only want to see invoices with a due date in May 2024. Please modify the query.

[Assistant] SELECT invoice_number, issue_date, due_date FROM legal_services.invoices WHERE due_date >= '2024-05-01' AND due_date < '2024-06-01' ORDER BY issue_date ASC;

[User] Also, only include invoices that have not been paid in full yet (amount_paid < total_amount).

[Assistant] SELECT invoice_number, issue_date, due_date FROM legal_services.invoices WHERE due_date >= '2024-05-01' AND due_date < '2024-06-01' AND amount_paid < total_amount ORDER BY issue_date ASC;

[User] Add the status column and sort the results by due_date descending.

[Assistant] SELECT invoice_number, issue_date, due_date, status FROM legal_services.invoices WHERE due_date >= '2024-05-01' AND due_date < '2024-06-01' AND amount_paid < total_amount ORDER BY due_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 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 )

[User] Find pairs of trades that share the same order_id but have different trade_types.

[Assistant]
SELECT a.order_id, a.trade_id AS trade_a, a.trade_type AS type_a, b.trade_id AS trade_b, b.trade_type AS type_b
FROM financial_services.trades a
JOIN financial_services.trades b
  ON a.order_id = b.order_id
  AND a.trade_type <> b.trade_type
  AND a.trade_id < b.trade_id;

[User] Only include pairs for orders executed in January 2023 with status 'COMPLETED' on both trades.

[Assistant]
SELECT a.order_id, a.trade_id AS trade_a, a.trade_type AS type_a, b.trade_id AS trade_b, b.trade_type AS type_b
FROM financial_services.trades a
JOIN financial_services.trades b
  ON a.order_id = b.order_id
  AND a.trade_type <> b.trade_type
  AND a.trade_id < b.trade_id
WHERE a.trade_timestamp BETWEEN '2023-01-01' AND '2023-01-31'
  AND b.trade_timestamp BETWEEN '2023-01-01' AND '2023-01-31'
  AND a.status = 'COMPLETED'
  AND b.status = 'COMPLETED';

[User] Order the results by order_id and then by trade_a's trade_timestamp.

[Assistant]
SELECT a.order_id, a.trade_id AS trade_a, a.trade_type AS type_a, b.trade_id AS trade_b, b.trade_type AS type_b
FROM financial_services.trades a
JOIN financial_services.trades b
  ON a.order_id = b.order_id
  AND a.trade_type <> b.trade_type
  AND a.trade_id < b.trade_id
WHERE a.trade_timestamp BETWEEN '2023-01-01' AND '2023-01-31'
  AND b.trade_timestamp BETWEEN '2023-01-01' AND '2023-01-31'
  AND a.status = 'COMPLETED'
  AND b.status = 'COMPLETED'
ORDER BY a.order_id, a.trade_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 hospitality_technology.reviews ( review_id character varying(64) NOT NULL, property_id character varying(64) NOT NULL, reservation_id character varying(64) UNIQUE, guest_id character varying(64) NOT NULL, rating_overall integer, rating_cleanliness integer, rating_service integer, rating_location integer, rating_value integer, comment text, review_source character varying(100), review_date timestamp with time zone NOT NULL DEFAULT current_timestamp, is_public boolean DEFAULT true, staff_response text, response_staff_id character varying(64), response_date timestamp with time zone, PRIMARY KEY (review_id), FOREIGN KEY (property_id) REFERENCES hospitality_technology.properties(property_id), FOREIGN KEY (reservation_id) REFERENCES hospitality_technology.reservations(reservation_id), FOREIGN KEY (guest_id) REFERENCES hospitality_technology.guests(guest_id), FOREIGN KEY (response_staff_id) REFERENCES hospitality_technology.staff(staff_id) )

[User] Identify all pairs of reviews where the same guest reviewed the same property twice, listing both review IDs.

[Assistant]
SELECT
  r1.guest_id,
  r1.property_id,
  r1.review_id AS review_a,
  r2.review_id AS review_b
FROM hospitality_technology.reviews r1
JOIN hospitality_technology.reviews r2
  ON r1.guest_id = r2.guest_id
  AND r1.property_id = r2.property_id
  AND r1.review_id < r2.review_id;

[User] Only include pairs where the two reviews were submitted within 30 days of each other.

[Assistant]
SELECT
  r1.guest_id,
  r1.property_id,
  r1.review_id AS review_a,
  r2.review_id AS review_b
FROM hospitality_technology.reviews r1
JOIN hospitality_technology.reviews r2
  ON r1.guest_id = r2.guest_id
  AND r1.property_id = r2.property_id
  AND r1.review_id < r2.review_id
  AND ABS(EXTRACT(EPOCH FROM (r2.review_date - r1.review_date)) / 86400) <= 30;

[User] Also include a column called review_gap_days that shows the number of days between the two review dates (rounded to two decimals).

[Assistant]
SELECT
  r1.guest_id,
  r1.property_id,
  r1.review_id AS review_a,
  r2.review_id AS review_b,
  ROUND(ABS(EXTRACT(EPOCH FROM (r2.review_date - r1.review_date))) / 86400, 2) AS review_gap_days
FROM hospitality_technology.reviews r1
JOIN hospitality_technology.reviews r2
  ON r1.guest_id = r2.guest_id
  AND r1.property_id = r2.property_id
  AND r1.review_id < r2.review_id
  AND ABS(EXTRACT(EPOCH FROM (r2.review_date - r1.review_date)) / 86400) <= 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 social_media.posts ( post_id.text, user_id.text, content.text, media_url.text, media_type.text, created_at.timestamp, updated_at.timestamp, visibility.text, location_lat.numeric, location_lon.numeric )
CREATE TABLE social_media.hashtags ( hashtag_id.text, tag_name.text, created_at.timestamp )
CREATE TABLE social_media.post_hashtags ( post_hashtag_id character varying(64) NOT NULL, post_id character varying(64) NOT NULL, hashtag_id character varying(64) NOT NULL, PRIMARY KEY (post_hashtag_id), CONSTRAINT unique_post_hashtag UNIQUE (post_id, hashtag_id) )
CREATE TABLE social_media.messages ( message_id text PRIMARY KEY, conversation_id text, sender_user_id text, content text, media_url text, media_type text, sent_at timestamp, read_at timestamp )
CREATE TABLE social_media.conversation_participants ( participant_id text, conversation_id text, user_id text, joined_at timestamp, last_read_at timestamp )
CREATE TABLE social_media.notifications (
    notification_id character varying(64) NOT NULL, -- unique identifier for the notification
    recipient_user_id character varying(64) NOT NULL, -- user receiving the notification (FK to users.user_id)
    sender_user_id character varying(64), -- user triggering the notification (FK to users.user_id, can be null for system notifications)
    notification_type character varying(30) NOT NULL, -- type of notification ('like', 'comment', 'follow', 'mention', 'message')
    target_entity_id character varying(64), -- ID of the related entity (post_id, comment_id, user_id, conversation_id)
    target_entity_type character varying(20), -- type of the related entity ('post', 'comment', 'user', 'conversation')
    created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, -- timestamp notification was created
    read_at timestamp, -- timestamp notification was marked as read
    PRIMARY KEY (notification_id)
)

[User] List all notifications related to messages. Please show notification_id, recipient_user_id, conversation_id, and the creation time.

[Assistant]
SELECT notification_id, recipient_user_id, target_entity_id AS conversation_id, created_at
FROM social_media.notifications
WHERE notification_type = 'message' AND target_entity_type = 'conversation';

[User] Actually, please only include notifications that haven't been read yet.

[Assistant]
SELECT notification_id, recipient_user_id, target_entity_id AS conversation_id, created_at
FROM social_media.notifications
WHERE notification_type = 'message' AND target_entity_type = 'conversation' AND read_at IS NULL;

[User] Could you also show the sender_user_id for each notification?

[Assistant]
SELECT notification_id, recipient_user_id, sender_user_id, target_entity_id AS conversation_id, created_at
FROM social_media.notifications
WHERE notification_type = 'message' AND target_entity_type = 'conversation' AND read_at IS NULL;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE 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.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 all insurance products of type 'Travel', including their product_id, product_name, and base_premium.

[Assistant]
SELECT product_id, product_name, base_premium
FROM insurance.insurance_products
WHERE product_type = 'Travel';


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 smart_money_token_performance ( token_address.text, token_symbol.text, pnl.numeric, net_flow.numeric, avg_cost.numeric, price.numeric, realized_ratio.numeric, roi.numeric, chain.text )

[User] List all smart money addresses that have a negative PNL but a positive Realized Ratio. Show the address, chain, PNL, and Realized Ratio.

[Assistant] SELECT token_address, chain, pnl, realized_ratio FROM smart_money_token_performance WHERE pnl < 0 AND realized_ratio > 0

[User] Can you refine the results to only include addresses where the absolute value of PNL is greater than 1000?

[Assistant] SELECT token_address, chain, pnl, realized_ratio FROM smart_money_token_performance WHERE pnl < -1000 AND realized_ratio > 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 social_media.hashtags ( hashtag_id character varying(64) NOT NULL, tag_name character varying(100) NOT NULL UNIQUE, created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, PRIMARY KEY (hashtag_id) )

[User] Count the total number of hashtags.

[Assistant] SELECT COUNT(*) FROM social_media.hashtags;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE token_metas ( block_timestamp.timestamp, block_number.bigint, transaction_hash.text, transaction_index.bigint, from_address.text, contract_address.text, symbol.text, total_supply.text, name.text, decimals.bigint, is_erc20.integer, is_erc721.integer, is_erc1155.integer, is_proxy.integer, extra_info.text, pk.integer )
CREATE TABLE erc1155_approval_for_all (
    block_number bigint NOT NULL, -- Block number containing the transaction
    block_timestamp timestamp(3) NOT NULL, -- Timestamp of the block containing the transaction
    transaction_index integer NOT NULL, -- Index of the transaction within the block
    transaction_hash varchar(66) NOT NULL, -- Transaction hash
    log_index integer NOT NULL, -- Log index
    contract_address varchar(42) NOT NULL  -- Event contract address
)
CREATE TABLE nft_holders ( block_number bigint NOT NULL, contract_address varchar NOT NULL, wallet_address varchar NOT NULL, token_id varchar NOT NULL, contract_type varchar NOT NULL, amount varchar NOT NULL, pk varchar NOT NULL )
CREATE TABLE nft_holder_historical ( block_number bigint NOT NULL, contract_address varchar NOT NULL, wallet_address varchar NOT NULL, token_id varchar NOT NULL, contract_type varchar NOT NULL, amount varchar NOT NULL, pk integer NOT NULL )
CREATE TABLE sui_coins ( object_id varchar NOT NULL, status varchar NOT NULL, coin_type varchar NOT NULL, balance varchar NOT NULL, owner varchar NOT NULL )
CREATE TABLE sui_coins_metadata (
    object_id varchar NOT NULL, -- object id of the coin metadata object
    coin_type varchar NOT NULL, -- coin type, eg. 0x...66::reap_token::REAP_TOKEN
    status varchar NOT NULL, -- coin status, eg. exists, deleted
    decimals bigint NOT NULL, -- decimals of the coin
    description varchar NOT NULL, -- description of the coin
    icon_url varchar NOT NULL, -- icon url of the coin
    symbol varchar NOT NULL, -- symbol of the coin
    name varchar NOT NULL  -- name of the coin
)
CREATE TABLE sui_nfts ( object_id text, status text, collection_type text, package_id text, previous_transaction text, display text, owner text, name text )
CREATE TABLE nft_metadata ( blockchain text, contract_address text, token_id text, contract_name text, erc_type text, amount bigint, minter text, owner text, mint_block_number bigint, mint_time bigint, mint_transaction_hash text, mint_price text, token_uri text, metadata text, name text, image_uri text, traits text, updated_at bigint, status text, rarity_score real, rarity_rank integer, unique_attribute_count integer, pk integer )
CREATE TABLE nft_collections ( blockchain varchar NOT NULL, contract_address varchar NOT NULL, name varchar NOT NULL, symbol varchar NOT NULL, deploy_block_number bigint NOT NULL, deploy_block_time bigint NOT NULL, erc_type varchar NOT NULL, owner varchar NOT NULL, traits varchar NOT NULL, description varchar NOT NULL, slug varchar NOT NULL, media_info varchar NOT NULL, image_url varchar NOT NULL, banner_image_url varchar NOT NULL, updated_at bigint NOT NULL, banner varchar NOT NULL, token_count bigint NOT NULL, floor_price varchar NOT NULL, floor_price_symbol varchar NOT NULL, floor_price_contract varchar NOT NULL, pk integer NOT NULL )
CREATE TABLE token_prices ( uuid text, blockchain text, address text, decimals bigint, symbol text, price real, timestamp timestamp )
CREATE TABLE erc20_approval ( block_number bigint NOT NULL, block_timestamp timestamp(6) NOT NULL, transaction_index integer NOT NULL, transaction_hash varchar NOT NULL, log_index integer NOT NULL, contract_address varchar NOT NULL, pk integer NOT NULL )
CREATE TABLE token_balances ( block_number.bigint, block_timestamp.timestamp, tick.text, wallet_address.text, total_supply.decimal, amount.decimal )
CREATE TABLE token_info (
    block_timestamp timestamp(3) NOT NULL, -- Timestamp of the block containing the inscription (matches block_timestamp in transactions table)
    block_number bigint NOT NULL, -- Block number containing the inscription (matches block_number in transactions table)
    tx_index integer NOT NULL, -- Index of the transaction containing the inscription (matches transaction_index in transactions table)
    tx_hash varchar(66) NOT NULL, -- Unique identifier of the transaction containing the inscription (matches hash in transactions table)
    tick varchar NOT NULL, -- Token tick
    max_supply decimal(38,0) NOT NULL, -- Max supply
    lim decimal(38,0) NOT NULL, -- Limit of each mint
    wlim decimal(38,0) NOT NULL, -- Limit of each address can maximum mint
    dec integer NOT NULL, -- Decimal for minimum divie
    creator varchar(42) NOT NULL  -- Address originating the inscription (matches from_address in transactions table)
)
CREATE TABLE mud_holesky_redstone (
    address varchar NOT NULL, -- address fields for the functionType  in contract
    table_id varchar NOT NULL, -- table_id fields for the functionType  in contract
    key_bytes varchar NOT NULL, -- key_bytes fields for the functionType  in contract
    key0 varchar NOT NULL, -- key0 fields for the functionType  in contract
    key1 varchar NOT NULL, -- key1 fields for the functionType  in contract
    static_data varchar NOT NULL, -- static_data fields for the functionType  in contract
    encoded_lengths varchar NOT NULL, -- encoded_lengths fields for the functionType  in contract
    dynamic_data varchar NOT NULL, -- dynamic_data fields for the functionType  in contract
    is_deleted boolean NOT NULL, -- is_deleted fields for the functionType  in contract
    block_number bigint NOT NULL, -- Block number uniquely identifying the block
    log_index bigint NOT NULL  -- Index of the log within the transaction
)
CREATE TABLE token_balances_bitcoin ( block_number bigint, block_timestamp timestamp, tick text, wallet_address text, total_supply text, amount text )
CREATE TABLE token_info_bitcoin ( block_timestamp.timestamp, block_number.bigint, tx_index.integer, tx_hash.text, tick.text, max_supply.decimal, lim.decimal, wlim.decimal, dec.integer, creator.text )
CREATE TABLE token_activities_bitcoin ( block_timestamp timestamp, block_number bigint, tx_index integer, tx_hash text, log_index integer, type text, tick text, id text, amt decimal, from_address text, to_address text )
CREATE TABLE token_activities_avalanche (
    block_timestamp timestamp(3) NOT NULL, -- Timestamp of the block containing the inscription (matches block_timestamp in transactions table)
    block_number bigint NOT NULL, -- Block number containing the inscription (matches block_number in transactions table)
    tx_index integer NOT NULL, -- Index of the transaction containing the inscription (matches transaction_index in transactions table)
    tx_hash varchar(66) NOT NULL, -- Unique identifier of the transaction containing the inscription (matches hash in transactions table)
    log_index integer NOT NULL, -- Index of the log within the transaction
    type varchar(20) NOT NULL, -- Operation: Type of event (deploy, mint, transfer, list)
    tick varchar(255) NOT NULL, -- Ticker: Identifier of the inscription
    id varchar(255) NOT NULL, -- Unique identifier of the inscription
    amt decimal(38,0) NOT NULL, -- Amount to mint: States the amount of the inscription to operation. When operation is mint, has to be less or equal to "lim"
    from_address varchar(42) NOT NULL, -- Address sending the inscription
    to_address varchar(42) NOT NULL  -- Address receiving the inscription
)

[User] Which ERC20 tokens have more than 8 decimals? Show their symbol, name, and decimals.

[Assistant]
SELECT symbol, name, decimals
FROM token_metas
WHERE is_erc20 = 1 AND decimals > 8;

[User] Can you also show the contract address and the total supply for each of these tokens?

[Assistant]
SELECT contract_address, symbol, name, decimals, total_supply
FROM token_metas
WHERE is_erc20 = 1 AND decimals > 8;

[User] Now, include only tokens where total_supply is greater than '100000000000' and order the results by total_supply descending.

[Assistant]
SELECT contract_address, symbol, name, decimals, total_supply
FROM token_metas
WHERE is_erc20 = 1 AND decimals > 8 AND total_supply > '100000000000'
ORDER BY total_supply 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 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 narrative_info ( narrative text, top_3_coins text, price_change_percentage_1h numeric, price_change_percentage_24h numeric, price_change_percentage_7d numeric, market_cap numeric, volume_24h numeric, trend_rank numeric, token_num numeric )
CREATE TABLE cex_token_balance ( snapshot_time text, chain text, address text, exchange text, token_address text, token_symbol text, balance numeric, usd_value numeric, price numeric )
CREATE TABLE smart_money_profit ( address text, rank numeric, profit numeric, roi numeric, realized_ratio numeric, most_profit_token text, last_trade_time text, chain text )
CREATE TABLE smart_money_token_inflow ( token_address text, token_symbol text, token_amount numeric, usd_value numeric, avg_price numeric, type numeric, address_amount numeric, narrative text, chain text )

[User] For the 'DeFi' narrative, what is the average ROI and the total net inflow (usd_value where type=1) from smart money token inflow?

[Assistant]
SELECT AVG(sm.roi) AS avg_roi, SUM(smt.usd_value) AS total_net_inflow
FROM smart_money_token_inflow smt
JOIN smart_money_profit sm ON smt.chain = sm.chain
WHERE smt.narrative = 'DeFi' AND smt.type = 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 social_media.users ( user_id text, username text, email text, password_hash text, full_name text, profile_picture_url text, bio text, location text, created_at timestamp, updated_at timestamp, is_verified boolean )
CREATE TABLE social_media.posts ( post_id character varying(64) NOT NULL, user_id character varying(64) NOT NULL, content text, media_url text, media_type character varying(20), created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, updated_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, visibility character varying(20) NOT NULL DEFAULT 'public', location_lat numeric(9,6), location_lon numeric(9,6), PRIMARY KEY (post_id) )
CREATE TABLE social_media.comments (
    comment_id character varying(64) NOT NULL, -- unique identifier for the comment
    post_id character varying(64) NOT NULL, -- identifier of the post being commented on (FK to posts.post_id)
    user_id character varying(64) NOT NULL, -- identifier of the user who made the comment (FK to users.user_id)
    parent_comment_id character varying(64), -- identifier of the parent comment if it's a reply (FK to comments.comment_id)
    content text NOT NULL, -- textual content of the comment
    created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, -- timestamp of comment creation
    updated_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, -- timestamp of last comment edit
    PRIMARY KEY (comment_id)
)
CREATE TABLE social_media.likes ( like_id.text, user_id.text, post_id.text, comment_id.text, created_at.timestamp )
CREATE TABLE social_media.follows ( follow_id text PRIMARY KEY, follower_user_id text, following_user_id text, created_at timestamp )
CREATE TABLE social_media.post_hashtags (
    post_hashtag_id character varying(64) NOT NULL, -- unique identifier for the post-hashtag link
    post_id character varying(64) NOT NULL, -- identifier of the post (FK to posts.post_id)
    hashtag_id character varying(64) NOT NULL, -- identifier of the hashtag (FK to hashtags.hashtag_id)
    PRIMARY KEY (post_hashtag_id),
    CONSTRAINT unique_post_hashtag UNIQUE (post_id, hashtag_id) -- prevent duplicate tags on a post
)
CREATE TABLE social_media.messages ( message_id text PRIMARY KEY, conversation_id text, sender_user_id text, content text, media_url text, media_type text, sent_at timestamp, read_at timestamp )
CREATE TABLE social_media.conversations (
    conversation_id character varying(64) NOT NULL, -- unique identifier for the conversation
    created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, -- timestamp when conversation was initiated
    last_message_at timestamp, -- timestamp of the last message in the conversation
    is_group_chat boolean NOT NULL DEFAULT false, -- indicates if it's a group chat or direct message
    group_name character varying(100), -- name of the group chat (if applicable)
    PRIMARY KEY (conversation_id)
)
CREATE TABLE social_media.conversation_participants ( participant_id text PRIMARY KEY, conversation_id text, user_id text, joined_at timestamp, last_read_at timestamp )
CREATE TABLE social_media.notifications ( notification_id.text, recipient_user_id.text, sender_user_id.text, notification_type.text, target_entity_id.text, target_entity_type.text, created_at.timestamp, read_at.timestamp )
CREATE TABLE social_media.user_settings ( setting_id text, user_id text, theme text, email_notifications_enabled boolean, push_notifications_enabled boolean, private_profile boolean, updated_at timestamp )

[User] Which users have commented on posts that contain media? Please show the commenter username and the post ID.

[Assistant]
SELECT DISTINCT u.username, c.post_id
FROM social_media.comments c
JOIN social_media.users u ON c.user_id = u.user_id
JOIN social_media.posts p ON c.post_id = p.post_id
WHERE p.media_url IS NOT NULL AND p.media_url <> '';

[User] Can you also include the content of the comment and the type of media for each post?

[Assistant]
SELECT u.username, c.post_id, c.content AS comment_content, p.media_type
FROM social_media.comments c
JOIN social_media.users u ON c.user_id = u.user_id
JOIN social_media.posts p ON c.post_id = p.post_id
WHERE p.media_url IS NOT NULL AND p.media_url <> '';

[User] Now only show comments that were created after May 1, 2024, and include the comment creation time.

[Assistant]
SELECT u.username, c.post_id, c.content AS comment_content, p.media_type, c.created_at AS comment_created_at
FROM social_media.comments c
JOIN social_media.users u ON c.user_id = u.user_id
JOIN social_media.posts p ON c.post_id = p.post_id
WHERE p.media_url IS NOT NULL AND p.media_url <> ''
  AND c.created_at > '2024-05-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 gaming_technology.developers ( developer_id uuid PRIMARY KEY, name text, country text, founded_year int, website text, created_at timestamptz )

[User] Find all pairs of developers in the same country but founded in different years. Show developer1, developer2, country, founded_year of each.

[Assistant]
SELECT d1.name AS developer1,
       d2.name AS developer2,
       d1.country,
       d1.founded_year AS founded1,
       d2.founded_year AS founded2
FROM gaming_technology.developers d1
JOIN gaming_technology.developers d2
  ON d1.country = d2.country
 AND d1.developer_id < d2.developer_id
 AND d1.founded_year <> d2.founded_year;

[User] Now only include pairs where the difference in founded_year is at least 15 years.

[Assistant]
SELECT d1.name AS developer1,
       d2.name AS developer2,
       d1.country,
       d1.founded_year AS founded1,
       d2.founded_year AS founded2
FROM gaming_technology.developers d1
JOIN gaming_technology.developers d2
  ON d1.country = d2.country
 AND d1.developer_id < d2.developer_id
 AND ABS(d1.founded_year - d2.founded_year) >= 15;


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
Index 'aircraft_models'. Mapping: { properties: { model_id: { type: 'keyword' }, model_name: { type: 'text', fields: { keyword: { type: 'keyword', ignore_above: 256 } } }, manufacturer: { type: 'keyword' }, passenger_capacity: { type: 'integer' }, max_range_km: { type: 'integer' }, engine_type: { type: 'keyword' }, wingspan_m: { type: 'float' }, status: { type: 'keyword' }, first_flight_date: { type: 'date' } } }. Document _id can be set to model_id.
Index 'components'. Mapping: { properties: { component_id: { type: 'keyword' }, part_number: { type: 'keyword' }, component_name: { type: 'text', fields: { keyword: { type: 'keyword', ignore_above: 256 } } }, description: { type: 'text' }, material_id: { type: 'keyword' }, supplier_id: { type: 'keyword' }, weight_kg: { type: 'scaled_float', scaling_factor: 1000 }, cost_usd: { type: 'scaled_float', scaling_factor: 100 }, criticality_level: { type: 'keyword' } } }. Document _id can be component_id.
Index 'materials'. Mapping: { properties: { material_id: { type: 'keyword' }, material_name: { type: 'text', fields: { keyword: { type: 'keyword', ignore_above: 256 } } }, specification: { type: 'keyword' }, description: { type: 'text' }, density_kg_m3: { type: 'float' }, tensile_strength_mpa: { type: 'integer' } } }. Document _id can be material_id.
Index 'assembly_lines'. Mapping: { properties: { line_id: { type: 'keyword' }, line_name: { type: 'text', fields: { keyword: { type: 'keyword', ignore_above: 256 } } }, location_building: { type: 'keyword' }, location_area: { type: 'keyword' }, aircraft_model_id: { type: 'keyword' }, capacity_units_per_month: { type: 'integer' }, status: { type: 'keyword' } } }. Document _id can be line_id.
Index 'assembly_steps'. Mapping: { properties: { step_id: { type: 'keyword' }, line_id: { type: 'keyword' }, step_number: { type: 'integer' }, step_name: { type: 'text', fields: { keyword: { type: 'keyword', ignore_above: 256 } } }, description: { type: 'text' }, standard_duration_hours: { type: 'float' }, required_skill_level: { type: 'keyword' }, workstation: { type: 'keyword' } } }. Document _id can be step_id.
Index 'aircraft_builds'. Mapping: { properties: { build_id: { type: 'keyword' }, serial_number: { type: 'keyword' }, model_id: { type: 'keyword' }, assembly_line_id: { type: 'keyword' }, build_start_date: { type: 'date' }, estimated_completion_date: { type: 'date' }, actual_completion_date: { type: 'date' }, current_status: { type: 'keyword' }, customer_order_id: { type: 'keyword' } } }. Document _id can be build_id.
Index 'inspections'. Mapping: { properties: { inspection_id: { type: 'keyword' }, build_id: { type: 'keyword' }, component_id: { type: 'keyword' }, step_id: { type: 'keyword' }, inspection_type: { type: 'keyword' }, inspector_employee_id: { type: 'keyword' }, inspection_timestamp: { type: 'date' }, result: { type: 'keyword' }, remarks: { type: 'text' } } }. Document _id can be inspection_id. Consider parent/child relationship with build_id for routing.
Index 'component_inventory'. Mapping: { properties: { inventory_record_id: { type: 'keyword' }, component_id: { type: 'keyword' }, quantity: { type: 'integer' }, location_warehouse: { type: 'keyword' }, location_bin: { type: 'keyword' }, received_date: { type: 'date' }, expiry_date: { type: 'date' }, batch_number: { type: 'keyword' }, last_updated: { type: 'date' } } }. Document _id can be inventory_record_id.

[User] Can you help me retrieve a list of all aircraft builds for a specific model, including their assembly line details and current status?

[Assistant]
SELECT ab.build_id, ab.serial_number, ab.model_id, ab.current_status, al.line_name, al.location_building, al.location_area
FROM aircraft_builds ab
JOIN assembly_lines al ON ab.assembly_line_id = al.line_id
WHERE ab.model_id = 'specific_model_id';

[User] Can you filter this to show only builds that started after a specific date, for example, January 1, 2022?

[Assistant]
SELECT ab.build_id, ab.serial_number, ab.model_id, ab.current_status, al.line_name, al.location_building, al.location_area
FROM aircraft_builds ab
JOIN assembly_lines al ON ab.assembly_line_id = al.line_id
WHERE ab.model_id = 'specific_model_id' AND ab.build_start_date > '2022-01-01';

[User] What if I want to include only builds that are not yet completed?

[Assistant]
SELECT ab.build_id, ab.serial_number, ab.model_id, ab.current_status, al.line_name, al.location_building, al.location_area
FROM aircraft_builds ab
JOIN assembly_lines al ON ab.assembly_line_id = al.line_id
WHERE ab.model_id = 'specific_model_id' AND ab.build_start_date > '2022-01-01' AND ab.actual_completion_date IS NULL;

[User] Can you also sort the results by build start date in ascending order?

[Assistant]
SELECT ab.build_id, ab.serial_number, ab.model_id, ab.current_status, al.line_name, al.location_building, al.location_area
FROM aircraft_builds ab
JOIN assembly_lines al ON ab.assembly_line_id = al.line_id
WHERE ab.model_id = 'specific_model_id' AND ab.build_start_date > '2022-01-01' AND ab.actual_completion_date IS NULL
ORDER BY ab.build_start_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 hospitality_technology.room_types ( room_type_id text, property_id text, type_name text, description text, base_rate numeric, max_occupancy integer, bed_type text, area_sqft numeric, amenities text )

[User] List all room types that have a King bed and include their maximum occupancy and amenities.

[Assistant] SELECT type_name, max_occupancy, amenities FROM hospitality_technology.room_types WHERE bed_type = 'King';

[User] Please sort them by maximum occupancy in ascending order.

[Assistant] SELECT type_name, max_occupancy, amenities FROM hospitality_technology.room_types WHERE bed_type = 'King' ORDER BY max_occupancy 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 project_fundraising_record ( id.text, project_id.text, project_name.text, rounds_name.text, investment_value.numeric, investment_date.text, introduction.text, valuation.numeric )

[User] Which project raised the highest investment_value in each fundraising round?

[Assistant]
SELECT p.project_name, p.rounds_name, p.investment_value AS max_investment
FROM project_fundraising_record p
JOIN (
    SELECT rounds_name, MAX(investment_value) AS max_investment
    FROM project_fundraising_record
    GROUP BY rounds_name
) m ON p.rounds_name = m.rounds_name AND p.investment_value = m.max_investment;

[User] Can you also include the project's valuation and introduction?

[Assistant]
SELECT p.project_name, p.rounds_name, p.investment_value AS max_investment, p.valuation, p.introduction
FROM project_fundraising_record p
JOIN (
    SELECT rounds_name, MAX(investment_value) AS max_investment
    FROM project_fundraising_record
    GROUP BY rounds_name
) m ON p.rounds_name = m.rounds_name AND p.investment_value = m.max_investment;

[User] Now, filter to only rounds where the maximum investment_value is greater than 2000000.

[Assistant]
SELECT p.project_name, p.rounds_name, p.investment_value AS max_investment, p.valuation, p.introduction
FROM project_fundraising_record p
JOIN (
    SELECT rounds_name, MAX(investment_value) AS max_investment
    FROM project_fundraising_record
    GROUP BY rounds_name
    HAVING MAX(investment_value) > 2000000
) m ON p.rounds_name = m.rounds_name AND p.investment_value = m.max_investment;

[User] Actually, only consider rounds in 2022 and order the results by the maximum investment_value descending.

[Assistant]
SELECT p.project_name, p.rounds_name, p.investment_value AS max_investment, p.valuation, p.introduction
FROM project_fundraising_record p
JOIN (
    SELECT rounds_name, MAX(investment_value) AS max_investment
    FROM project_fundraising_record
    WHERE investment_date LIKE '2022-%'
    GROUP BY rounds_name
    HAVING MAX(investment_value) > 2000000
) m ON p.rounds_name = m.rounds_name AND p.investment_value = m.max_investment
ORDER BY m.max_investment DESC;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE trading_platform.wallets (
    wallet_id character varying(64) NOT NULL,  -- unique identifier for the wallet
    user_id character varying(64) NOT NULL, -- identifier of the user owning the wallet
    address character varying(128) NOT NULL, -- address of the wallet
    private_key text NOT NULL, -- private key of the wallet
    created_at timestamp NOT NULL, -- time when the wallet was created
    PRIMARY KEY (wallet_id)
)
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 character varying(64) NOT NULL,  -- unique identifier for the asset
    name character varying(128) NOT NULL, -- name of the asset
    symbol character varying(32) NOT NULL, -- symbol of the asset
    type character varying(32) NOT NULL, -- type of the asset (e.g., cryptocurrency, stock)
    PRIMARY KEY (asset_id)
)
CREATE TABLE trading_platform.utxos (
    utxo_id character varying(64) NOT NULL,  -- unique identifier for the UTXO
    transaction_id character varying(64) NOT NULL, -- identifier of the transaction that created the UTXO
    output_index integer NOT NULL, -- index of the output in the transaction
    address character varying(128) NOT NULL, -- address that can spend the UTXO
    amount numeric(38,14) NOT NULL, -- amount of the asset in the UTXO
    spent boolean NOT NULL, -- whether the UTXO has been spent
    PRIMARY KEY (utxo_id)
)
CREATE TABLE trading_platform.peers (
    peer_id character varying(64) NOT NULL,  -- unique identifier for the peer
    ip_address character varying(15) NOT NULL, -- IP address of the peer
    port integer NOT NULL, -- port number of the peer
    last_seen timestamp NOT NULL, -- last time the peer was active
    PRIMARY KEY (peer_id)
)
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.notifications (
    notification_id character varying(64) NOT NULL,  -- unique identifier for the notification
    user_id character varying(64) NOT NULL, -- identifier of the user receiving the notification
    message text NOT NULL, -- message of the notification
    sent_at timestamp NOT NULL, -- time when the notification was sent
    read_at timestamp, -- time when the notification was read
    PRIMARY KEY (notification_id)
)

[User] Give me all unspent UTXOs for address '1A2b3C4d5E', sorted by amount descending.

[Assistant]
SELECT utxo_id, transaction_id, output_index, address, amount
FROM trading_platform.utxos
WHERE address = '1A2b3C4d5E' AND spent = FALSE
ORDER BY amount DESC;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE trading_platform.trades ( trade_id character varying(64) NOT NULL, order_id character varying(64) NOT NULL, buyer_id character varying(64) NOT NULL, seller_id character varying(64) NOT NULL, asset_id character varying(64) NOT NULL, quantity numeric(38,14) NOT NULL, price numeric(38,14) NOT NULL, traded_at timestamp NOT NULL, PRIMARY KEY (trade_id) )

[User] Calculate the total quantity traded for each day in the dataset.

[Assistant] SELECT DATE_TRUNC('day', traded_at) AS trade_day, SUM(quantity) AS total_daily_quantity FROM trading_platform.trades GROUP BY DATE_TRUNC('day', traded_at) ORDER BY trade_day;

[User] Could you also include the total trade value (quantity * price) for each day in that report?

[Assistant] SELECT DATE_TRUNC('day', traded_at) AS trade_day, SUM(quantity) AS total_daily_quantity, SUM(quantity * price) AS total_daily_value FROM trading_platform.trades GROUP BY DATE_TRUNC('day', traded_at) ORDER BY trade_day;

[User] Now, for each day, show how the total quantity compares to the overall average daily quantity across all days in the dataset.

[Assistant] WITH DailySummary AS (SELECT DATE_TRUNC('day', traded_at) AS trade_day, SUM(quantity) AS total_daily_quantity FROM trading_platform.trades GROUP BY DATE_TRUNC('day', traded_at)) SELECT trade_day, total_daily_quantity, total_daily_quantity - AVG(total_daily_quantity) OVER () AS quantity_difference_from_average FROM DailySummary ORDER BY trade_day;

[User] Finally, only show the days where the total quantity was higher than the overall average daily quantity.

[Assistant] WITH DailySummary AS (SELECT DATE_TRUNC('day', traded_at) AS trade_day, SUM(quantity) AS total_daily_quantity FROM trading_platform.trades GROUP BY DATE_TRUNC('day', traded_at)) SELECT trade_day, total_daily_quantity FROM DailySummary WHERE total_daily_quantity > (SELECT AVG(total_daily_quantity) FROM DailySummary) ORDER BY trade_day;


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 )

[User] Count the number of patients whose address includes the word 'Street' and are male.

[Assistant] SELECT COUNT(*) FROM healthcare.patients WHERE address LIKE '%Street%' AND gender = 'Male';


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 nft_holders ( block_number bigint, contract_address text, wallet_address text, token_id text, contract_type text, amount text, pk text )
CREATE TABLE nft_holder_historical ( block_number bigint, contract_address text, wallet_address text, token_id text, contract_type text, amount text, pk integer )
CREATE TABLE sui_coins_metadata ( object_id text, coin_type text, status text, decimals bigint, description text, icon_url text, symbol text, name text )
CREATE TABLE nft_metadata ( blockchain text, contract_address text, token_id text, contract_name text, erc_type text, amount bigint, minter text, owner text, mint_block_number bigint, mint_time bigint, mint_transaction_hash text, mint_price text, token_uri text, metadata text, name text, image_uri text, traits text, updated_at bigint, status text, rarity_score real, rarity_rank integer, unique_attribute_count integer, pk integer )
CREATE TABLE nft_collections ( blockchain text, contract_address text, name text, symbol text, deploy_block_number bigint, deploy_block_time bigint, erc_type text, owner text, traits text, description text, slug text, media_info text, image_url text, banner_image_url text, updated_at bigint, banner text, token_count bigint, floor_price text, floor_price_symbol text, floor_price_contract text, pk integer )
CREATE TABLE token_prices_latest ( blockchain text, address text, decimals bigint, symbol text, price real, timestamp timestamp )
CREATE TABLE erc20_approval ( block_number bigint, block_timestamp timestamp, transaction_index integer, transaction_hash text, log_index integer, contract_address text, pk integer )
CREATE TABLE mud_holesky_redstone ( address text, table_id text, key_bytes text, key0 text, key1 text, static_data text, encoded_lengths text, dynamic_data text, is_deleted boolean, block_number bigint, log_index bigint )
CREATE TABLE token_balances_bitcoin ( block_number bigint, block_timestamp timestamp, tick text, wallet_address text, total_supply text, amount text )
CREATE TABLE token_info_bitcoin ( block_timestamp timestamp, block_number bigint, tx_index integer, tx_hash text, tick text, max_supply decimal, lim decimal, wlim decimal, dec integer, creator text )
CREATE TABLE token_activities_bitcoin ( block_timestamp timestamp, block_number bigint, tx_index integer, tx_hash text, log_index integer, type text, tick text, id text, amt decimal, from_address text, to_address text )
CREATE TABLE token_activities_avalanche ( block_timestamp timestamp, block_number bigint, tx_index integer, tx_hash text, log_index integer, type text, tick text, id text, amt decimal, from_address text, to_address text )
CREATE TABLE token_balances_avalanche ( block_number bigint, block_timestamp timestamp, tick text, wallet_address text, total_supply decimal, amount decimal )
CREATE TABLE token_info_avalanche ( block_timestamp timestamp, block_number bigint, tx_index integer, tx_hash text, tick text, max_supply decimal, lim decimal, wlim decimal, dec integer, creator text, minted decimal, holders decimal, txs decimal, updated_timestamp timestamp, completed_timestamp timestamp, id text )

[User] Show all SUI coin types with more than 6 decimals and status 'exists' in the metadata table.

[Assistant]
SELECT coin_type, symbol, name, decimals
FROM sui_coins_metadata
WHERE status = 'exists' AND decimals > 6;

[User] For each of these, can you show the total balance across all owners by joining sui_coins?

[Assistant]
SELECT scm.coin_type, scm.symbol, scm.name, scm.decimals, SUM(sc.balance) AS total_balance
FROM sui_coins_metadata scm
JOIN sui_coins sc ON scm.coin_type = sc.coin_type
WHERE scm.status = 'exists' AND sc.status = 'exists' AND scm.decimals > 6
GROUP BY scm.coin_type, scm.symbol, scm.name, scm.decimals;

[User] Limit the result to the top 5 coin types by total_balance.

[Assistant]
SELECT scm.coin_type, scm.symbol, scm.name, scm.decimals, SUM(sc.balance) AS total_balance
FROM sui_coins_metadata scm
JOIN sui_coins sc ON scm.coin_type = sc.coin_type
WHERE scm.status = 'exists' AND sc.status = 'exists' AND scm.decimals > 6
GROUP BY scm.coin_type, scm.symbol, scm.name, scm.decimals
ORDER BY total_balance 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 web3.wallets ( wallet_id text, user_id text, address text, private_key text, created_at timestamp )

[User] Which user has the earliest created wallet? Show the user_id, wallet_id, address, and the creation timestamp.

[Assistant]
SELECT user_id, wallet_id, address, created_at
FROM web3.wallets
ORDER BY created_at ASC
LIMIT 1;

[User] Can you show all users whose earliest wallet was created on '2023-01-01'? Please include their user_id, wallet_id, and wallet address.

[Assistant]
SELECT w.user_id, w.wallet_id, w.address
FROM web3.wallets w
INNER JOIN (
  SELECT user_id, MIN(created_at) AS min_created_at
  FROM web3.wallets
  GROUP BY user_id
) first_wallet ON w.user_id = first_wallet.user_id AND w.created_at = first_wallet.min_created_at
WHERE w.created_at::date = '2023-01-01';


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE healthcare.patients (
    patient_id character varying(64) NOT NULL,  -- unique identifier for the patient
    first_name character varying(100) NOT NULL, -- patient's first name
    last_name character varying(100) NOT NULL, -- patient's last name
    date_of_birth date NOT NULL, -- patient's date of birth
    gender character varying(10), -- patient's gender (e.g., Male, Female, Other)
    address text, -- patient's home address
    phone_number character varying(20), -- patient's phone number
    email character varying(128) UNIQUE, -- patient's email address
    emergency_contact_name character varying(200), -- name of emergency contact
    emergency_contact_phone character varying(20), -- phone number of emergency contact
    created_at timestamp with time zone NOT NULL DEFAULT current_timestamp, -- record creation time
    updated_at timestamp with time zone NOT NULL DEFAULT current_timestamp, -- record last update time
    PRIMARY KEY (patient_id)
)
CREATE TABLE healthcare.doctors (
    doctor_id character varying(64) NOT NULL,  -- unique identifier for the doctor
    first_name character varying(100) NOT NULL, -- doctor's first name
    last_name character varying(100) NOT NULL, -- doctor's last name
    specialty character varying(100) NOT NULL, -- doctor's medical specialty
    license_number character varying(50) UNIQUE NOT NULL, -- doctor's medical license number
    phone_number character varying(20), -- doctor's contact phone
    email character varying(128) UNIQUE, -- doctor's contact email
    hospital_affiliation_id character varying(64), -- FK to hospitals table (optional)
    created_at timestamp with time zone NOT NULL DEFAULT current_timestamp,
    updated_at timestamp with time zone NOT NULL DEFAULT current_timestamp,
    PRIMARY KEY (doctor_id)
)
CREATE TABLE healthcare.appointments (
    appointment_id character varying(64) NOT NULL, -- unique identifier for the appointment
    patient_id character varying(64) NOT NULL, -- FK to patients table
    doctor_id character varying(64) NOT NULL, -- FK to doctors table
    appointment_time timestamp with time zone NOT NULL, -- date and time of the appointment
    duration_minutes integer NOT NULL, -- expected duration in minutes
    reason text, -- reason for the visit
    status character varying(32) NOT NULL, -- e.g., Scheduled, Completed, Cancelled, No-show
    location_id character varying(64), -- FK to a potential locations/clinics table
    notes text, -- notes related to scheduling
    created_at timestamp with time zone NOT NULL DEFAULT current_timestamp,
    PRIMARY KEY (appointment_id)
)
CREATE TABLE healthcare.medical_records (
    record_id character varying(64) NOT NULL,  -- unique identifier for the medical record entry
    patient_id character varying(64) NOT NULL, -- FK to patients table
    appointment_id character varying(64) UNIQUE, -- FK to appointments table (can be null if record not tied to specific appt)
    doctor_id character varying(64) NOT NULL, -- FK to doctors table (doctor creating the record)
    record_date timestamp with time zone NOT NULL, -- date the record/observation was made
    chief_complaint text, -- patient's primary reason for visit
    present_illness_history text, -- detailed history of the current issue
    past_medical_history text, -- relevant past conditions/surgeries
    physical_examination_notes text, -- findings from the physical exam
    assessment text, -- doctor's assessment/diagnosis summary
    treatment_plan text, -- planned course of action
    vitals jsonb, -- store vitals like BP, HR, Temp as structured JSON
    created_at timestamp with time zone NOT NULL DEFAULT current_timestamp,
    PRIMARY KEY (record_id)
)
CREATE TABLE healthcare.diagnoses (
    diagnosis_id character varying(64) NOT NULL, -- unique identifier for the diagnosis entry
    record_id character varying(64) NOT NULL, -- FK linking to the specific medical record entry
    patient_id character varying(64) NOT NULL, -- FK to patients table
    doctor_id character varying(64) NOT NULL, -- FK to doctors table (diagnosing doctor)
    diagnosis_code character varying(20) NOT NULL, -- standard code (e.g., ICD-10)
    code_type character varying(10) NOT NULL DEFAULT 'ICD-10', -- type of code used
    description text, -- textual description of the diagnosis
    diagnosis_date date NOT NULL, -- date the diagnosis was made
    status character varying(32) NOT NULL, -- e.g., Active, Resolved, Ruled Out
    is_chronic boolean DEFAULT false, -- flag for chronic conditions
    PRIMARY KEY (diagnosis_id)
)
CREATE TABLE healthcare.patient_insurance (
    patient_insurance_id character varying(64) NOT NULL, -- unique identifier for this patient-plan link
    patient_id character varying(64) NOT NULL, -- FK to patients table
    plan_id character varying(64) NOT NULL, -- FK to insurance_plans table
    policy_number character varying(100) NOT NULL, -- patient's policy number
    group_number character varying(100), -- group number, if applicable
    subscriber_name character varying(200), -- name of the primary policy holder
    effective_date date NOT NULL, -- date the coverage begins
    expiration_date date, -- date the coverage ends (if known)
    is_primary boolean NOT NULL DEFAULT true, -- indicates if this is the primary insurance
    PRIMARY KEY (patient_insurance_id),
    UNIQUE (patient_id, plan_id, policy_number) -- ensure a patient doesn't have the same policy twice
)

[User] Show the first and last names, date of birth, and phone number for all patients who have provided an emergency contact.

[Assistant]
SELECT first_name, last_name, date_of_birth, phone_number
FROM healthcare.patients
WHERE emergency_contact_name IS NOT NULL AND emergency_contact_name <> '';


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE healthcare.diagnoses ( diagnosis_id character varying(64) NOT NULL, record_id character varying(64) NOT NULL, patient_id character varying(64) NOT NULL, doctor_id character varying(64) NOT NULL, diagnosis_code character varying(20) NOT NULL, code_type character varying(10) NOT NULL DEFAULT 'ICD-10', description text, diagnosis_date date NOT NULL, status character varying(32) NOT NULL, is_chronic boolean DEFAULT false, PRIMARY KEY (diagnosis_id) )
CREATE TABLE healthcare.prescriptions ( prescription_id character varying(64) NOT NULL, record_id character varying(64) NOT NULL, patient_id character varying(64) NOT NULL, doctor_id character varying(64) NOT NULL, medication_id character varying(64) NOT NULL, dosage character varying(100) NOT NULL, frequency character varying(100) NOT NULL, route character varying(50), start_date date NOT NULL, end_date date, quantity_dispensed numeric(10,2), refills_allowed integer NOT NULL DEFAULT 0, prescription_date timestamp with time zone NOT NULL DEFAULT current_timestamp, PRIMARY KEY (prescription_id) )
CREATE TABLE healthcare.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] How many unique medications have ever been prescribed to each patient? Show patient_id and medication_count.

[Assistant]
SELECT patient_id, COUNT(DISTINCT medication_id) AS medication_count
FROM healthcare.prescriptions
GROUP BY patient_id;

[User] Only show patients who have been prescribed at least 5 unique medications.

[Assistant]
SELECT patient_id, COUNT(DISTINCT medication_id) AS medication_count
FROM healthcare.prescriptions
GROUP BY patient_id
HAVING COUNT(DISTINCT medication_id) >= 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 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.insurance_products ( product_id.text, product_name.text, product_type.text, description.text, base_premium.numeric, coverage_details.text, underwriting_rules.text, is_active.boolean, created_at.timestamp, updated_at.timestamp )

[User] List active policies where the premium amount is greater than the base premium of the linked insurance product. Show policy number, policy premium, product name, and product base premium.

[Assistant] SELECT T1.policy_number, T1.premium_amount, T2.product_name, T2.base_premium FROM insurance.policies AS T1 JOIN insurance.insurance_products AS T2 ON T1.product_id = T2.product_id WHERE T1.status = 'active' AND T1.premium_amount > T2.base_premium;

[User] Also, only include policies that were issued in the year 2023.

[Assistant] SELECT T1.policy_number, T1.premium_amount, T2.product_name, T2.base_premium FROM insurance.policies AS T1 JOIN insurance.insurance_products AS T2 ON T1.product_id = T2.product_id WHERE T1.status = 'active' AND T1.premium_amount > T2.base_premium AND EXTRACT(YEAR FROM T1.issued_at) = 2023;

[User] Could you sort the results by policy premium in descending order and limit to the top 10?

[Assistant] SELECT T1.policy_number, T1.premium_amount, T2.product_name, T2.base_premium FROM insurance.policies AS T1 JOIN insurance.insurance_products AS T2 ON T1.product_id = T2.product_id WHERE T1.status = 'active' AND T1.premium_amount > T2.base_premium AND EXTRACT(YEAR FROM T1.issued_at) = 2023 ORDER BY T1.premium_amount DESC LIMIT 10;