[User] Count how many appointments have been canceled at each location. Return the location and cancelled_count.

[Assistant]
SELECT location, COUNT(*) AS cancelled_count
FROM legal_services.appointments
WHERE status = 'Canceled'
GROUP BY location;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE legal_services.clients ( client_id text PRIMARY KEY, first_name text, last_name text, company_name text, email text UNIQUE, phone text, address text, date_registered timestamp, status text )
CREATE TABLE legal_services.lawyers (
    lawyer_id character varying(64) NOT NULL,  -- unique identifier for the lawyer
    first_name character varying(100) NOT NULL, -- lawyer's first name
    last_name character varying(100) NOT NULL, -- lawyer's last name
    bar_number character varying(64) UNIQUE NOT NULL, -- lawyer's bar association number
    firm_id character varying(64), -- FK to law_firms table
    email character varying(128) UNIQUE NOT NULL, -- lawyer's professional email
    phone character varying(32), -- lawyer's contact phone number
    specialization text, -- areas of legal expertise
    hire_date timestamp NOT NULL, -- date the lawyer was hired or joined
    is_partner boolean DEFAULT false, -- flag indicating if the lawyer is a partner
    PRIMARY KEY (lawyer_id)
)
CREATE TABLE legal_services.time_entries (
    entry_id character varying(64) NOT NULL,  -- unique identifier for the time entry
    case_id character varying(64) NOT NULL, -- FK to cases table
    lawyer_id character varying(64) NOT NULL, -- FK to lawyers table (who performed the work)
    date_worked date NOT NULL, -- date the work was performed
    hours_spent numeric(5, 2) NOT NULL CHECK (hours_spent > 0), -- duration of work in hours (e.g., 1.5 for 1h 30m)
    billing_rate numeric(10, 2) NOT NULL, -- hourly rate applied for this entry
    description text NOT NULL, -- detailed description of the work performed
    is_billable boolean DEFAULT true, -- whether this time entry is billable to the client
    is_billed boolean DEFAULT false, -- whether this entry has been included in an invoice
    invoice_id character varying(64), -- FK to invoices table (once billed)
    created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, -- when the entry was recorded
    PRIMARY KEY (entry_id)
)
CREATE TABLE legal_services.invoices ( invoice_id.text, invoice_number.text, client_id.text, case_id.text, issue_date.date, due_date.date, total_amount.numeric, amount_paid.numeric, status.text, payment_date.timestamp, notes.text, created_at.timestamp )
CREATE TABLE legal_services.appointments (
    appointment_id character varying(64) NOT NULL, -- unique identifier for the appointment
    client_id character varying(64) NOT NULL, -- FK to clients table
    lawyer_id character varying(64) NOT NULL, -- FK to lawyers table
    case_id character varying(64), -- FK to cases table (optional, if related to a specific case)
    start_time timestamp NOT NULL, -- scheduled start date and time
    end_time timestamp NOT NULL, -- scheduled end date and time
    location text, -- location of the meeting (address or virtual link)
    subject character varying(255), -- subject or purpose of the appointment
    notes text, -- additional notes for the appointment
    status character varying(50) NOT NULL, -- e.g., Scheduled, Completed, Canceled, Rescheduled
    created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
    PRIMARY KEY (appointment_id)
)


[User] List `user_id` and `conversation_id` for participants who are in conversations where there is at least one message sent by *another* user that they have not read.

[Assistant] SELECT DISTINCT T1.user_id, T1.conversation_id FROM social_media.conversation_participants AS T1 JOIN social_media.messages AS T2 ON T1.conversation_id = T2.conversation_id WHERE T2.sender_user_id != T1.user_id AND (T1.last_read_at IS NULL OR T2.sent_at > T1.last_read_at);

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE social_media.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.conversation_participants ( participant_id character varying(64) NOT NULL, conversation_id character varying(64) NOT NULL, user_id character varying(64) NOT NULL, joined_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, last_read_at timestamp, PRIMARY KEY (participant_id), CONSTRAINT unique_user_conversation UNIQUE (conversation_id, user_id) )


[User] List each child agency ID and name along with its parent agency ID and name.

[Assistant]
SELECT c.agency_id AS child_id,
       c.agency_name AS child_name,
       p.agency_id AS parent_id,
       p.agency_name AS parent_name
FROM government_services.agencies AS c
JOIN government_services.agencies AS p
  ON c.parent_agency_id = p.agency_id;

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


[User] Show me all business center services (category = 'Business Center') along with their property IDs and descriptions, where the service is available.

[Assistant] SELECT service_name, property_id, description FROM hospitality_technology.services WHERE category = 'Business Center' AND is_available = true;

[User] Now, join this with another query to include the property names from the properties table (assuming properties table has property_id and property_name columns).

[Assistant] SELECT s.service_name, s.property_id, s.description, p.property_name FROM hospitality_technology.services s JOIN hospitality_technology.properties p ON s.property_id = p.property_id WHERE s.category = 'Business Center' AND s.is_available = true;

[User] The query is missing the price information. Can you include that as well?

[Assistant] SELECT s.service_name, s.property_id, s.description, p.property_name, s.price FROM hospitality_technology.services s JOIN hospitality_technology.properties p ON s.property_id = p.property_id WHERE s.category = 'Business Center' AND s.is_available = true;

[User] Actually, I need to see only services priced per hour (unit = 'Per Hour'), and order them by property name in alphabetical order.

[Assistant] SELECT s.service_name, s.property_id, s.description, p.property_name, s.price FROM hospitality_technology.services s JOIN hospitality_technology.properties p ON s.property_id = p.property_id WHERE s.category = 'Business Center' AND s.is_available = true AND s.unit = 'Per Hour' ORDER BY p.property_name ASC;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE hospitality_technology.services (
    service_id character varying(64) NOT NULL, -- unique identifier for a chargeable service
    property_id character varying(64) NOT NULL, -- FK to properties table
    service_name character varying(150) NOT NULL, -- e.g., Room Service - Burger, Spa - Massage 60min, Laundry - Shirt
    description text,
    category character varying(100), -- e.g., Food & Beverage, Wellness, Business Center, Activities
    price numeric(10, 2) NOT NULL, -- price per unit/instance
    unit character varying(30), -- e.g., Per Item, Per Hour, Per Day
    is_available boolean NOT NULL DEFAULT true, -- is the service currently offered?
    department character varying(100), -- department responsible (e.g., F&B, Spa, Housekeeping)
    PRIMARY KEY (service_id),
    FOREIGN KEY (property_id) REFERENCES hospitality_technology.properties(property_id)
)


[User] What are the training programs or certifications completed by a staff member with the role of Platform Supervisor?

[Assistant] I'm sorry, but I don't have access to information about the training programs or certifications completed by staff members. The data available to me only includes basic staff details such as name, role, and contact information. For details on training or certifications, please refer to the HR department or relevant training records.

System:
You are an SQL statement expert and you can refuse the user's question if the question is not related to the table structure. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE train_station_management.staff ( staff_id text PRIMARY KEY, first_name text, last_name text, role text, primary_station_id text, employee_number text UNIQUE, hire_date date, contact_email text UNIQUE, contact_phone text, is_active boolean )


[User] Show me the average investment value for projects that completed fundraising in the last 6 months, grouped by round name.

[Assistant] SELECT rounds_name, AVG(investment_value) as avg_investment FROM project_fundraising_record WHERE investment_date >= date('now', '-6 months') GROUP BY rounds_name;

[User] I only want to see rounds where the average investment is over $1 million.

[Assistant] SELECT rounds_name, AVG(investment_value) as avg_investment FROM project_fundraising_record WHERE investment_date >= date('now', '-6 months') GROUP BY rounds_name HAVING avg_investment > 1000000;

[User] Can you also include the count of projects for each of these rounds?

[Assistant] SELECT rounds_name, AVG(investment_value) as avg_investment, COUNT(*) as project_count FROM project_fundraising_record WHERE investment_date >= date('now', '-6 months') GROUP BY rounds_name HAVING avg_investment > 1000000;

[User] Now order the results by project count in descending order.

[Assistant] SELECT rounds_name, AVG(investment_value) as avg_investment, COUNT(*) as project_count FROM project_fundraising_record WHERE investment_date >= date('now', '-6 months') GROUP BY rounds_name HAVING avg_investment > 1000000 ORDER BY project_count DESC;

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


[User] Find all wallets that were created on the same day and list their wallet IDs, addresses, and the creation date.

[Assistant] SELECT w1.wallet_id, w1.address, w1.created_at::date AS creation_date FROM web3.wallets w1 JOIN (SELECT created_at::date AS creation_date FROM web3.wallets GROUP BY created_at::date HAVING COUNT(*) > 1) w2 ON w1.created_at::date = w2.creation_date ORDER BY creation_date, w1.wallet_id;

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


[User] Show all wallet addresses together with the private key, sorted from the most recent to oldest creation date.

[Assistant] SELECT address, private_key, created_at FROM web3.wallets ORDER BY created_at DESC;

[User] Actually, could you also include the user_id for each wallet in the result?

[Assistant] SELECT user_id, address, private_key, created_at FROM web3.wallets ORDER BY created_at DESC;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE web3.wallets ( wallet_id text PRIMARY KEY, user_id text, address text, private_key text, created_at timestamp )


[User] Show me all pairs of time entries that are associated with the same invoice, including their entry IDs, lawyer IDs, and the shared invoice ID.

[Assistant]
SELECT te1.entry_id AS entry1_id,
       te2.entry_id AS entry2_id,
       te1.lawyer_id,
       te1.invoice_id
FROM legal_services.time_entries te1
JOIN legal_services.time_entries te2
  ON te1.invoice_id = te2.invoice_id
 AND te1.entry_id < te2.entry_id
WHERE te1.invoice_id IS NOT NULL;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE legal_services.time_entries (
    entry_id character varying(64) NOT NULL,  -- unique identifier for the time entry
    case_id character varying(64) NOT NULL, -- FK to cases table
    lawyer_id character varying(64) NOT NULL, -- FK to lawyers table (who performed the work)
    date_worked date NOT NULL, -- date the work was performed
    hours_spent numeric(5, 2) NOT NULL CHECK (hours_spent > 0), -- duration of work in hours (e.g., 1.5 for 1h 30m)
    billing_rate numeric(10, 2) NOT NULL, -- hourly rate applied for this entry
    description text NOT NULL, -- detailed description of the work performed
    is_billable boolean DEFAULT true, -- whether this time entry is billable to the client
    is_billed boolean DEFAULT false, -- whether this entry has been included in an invoice
    invoice_id character varying(64), -- FK to invoices table (once billed)
    created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, -- when the entry was recorded
    PRIMARY KEY (entry_id)
)


[User] Count the number of law firms founded in each decade. Show the decade (e.g., 1990s, 2000s) and the count.

[Assistant] SELECT CONCAT(FLOOR(EXTRACT(YEAR FROM founded_date) / 10) * 10, 's') AS decade, COUNT(*) AS firm_count FROM law_firms WHERE founded_date IS NOT NULL GROUP BY decade ORDER BY decade;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE legal_services.clients ( client_id text PRIMARY KEY, first_name text, last_name text, company_name text, email text UNIQUE, phone text, address text, date_registered timestamp, status text )
CREATE TABLE legal_services.law_firms ( firm_id text PRIMARY KEY, firm_name text, address text, phone text, website text, founded_date date, managing_partner_id text )
CREATE TABLE legal_services.documents ( document_id text PRIMARY KEY, case_id text, document_name text, document_type text, storage_path text, uploaded_by_lawyer_id text, upload_timestamp timestamp, version int, description text )


[User] Show the usernames of users who have followers and the total count of followers for each.

[Assistant] SELECT T1.username, COUNT(T2.follower_user_id) AS follower_count FROM social_media.users AS T1 JOIN social_media.follows AS T2 ON T1.user_id = T2.following_user_id GROUP BY T1.user_id, T1.username;

[User] Modify to only include users whose accounts were created after '2023-01-01'.

[Assistant] SELECT T1.username, COUNT(T2.follower_user_id) AS follower_count FROM social_media.users AS T1 JOIN social_media.follows AS T2 ON T1.user_id = T2.following_user_id WHERE T1.created_at > '2023-01-01' GROUP BY T1.user_id, T1.username;

[User] Order the results by follower count in descending order and limit to the top 10.

[Assistant] SELECT T1.username, COUNT(T2.follower_user_id) AS follower_count FROM social_media.users AS T1 JOIN social_media.follows AS T2 ON T1.user_id = T2.following_user_id WHERE T1.created_at > '2023-01-01' GROUP BY T1.user_id, T1.username ORDER BY follower_count DESC LIMIT 10;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE 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.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.comments ( comment_id.text, post_id.text, user_id.text, parent_comment_id.text, content.text, created_at.timestamp, updated_at.timestamp )
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, follower_user_id.text, following_user_id.text, created_at.timestamp )
CREATE TABLE social_media.conversation_participants ( participant_id.text, conversation_id.text, user_id.text, joined_at.timestamp, last_read_at.timestamp )


[User] Show me projects that completed a fundraising round in 2023 and have an associated token held by centralized exchanges. Display the project name, fundraising amount, the associated token symbol, and the total USD value of that token held by CEXes across all chains and snapshots.

[Assistant] SELECT pfr.project_name, pfr.investment_value, ctb.token_symbol, SUM(ctb.usd_value) AS total_cex_usd_value FROM project_fundraising_record AS pfr JOIN cex_token_balance AS ctb ON pfr.project_name = ctb.token_symbol WHERE pfr.investment_date LIKE '2023%' GROUP BY pfr.project_name, pfr.investment_value, ctb.token_symbol;

[User] Filter these results further to only include fundraising rounds named 'Seed' or 'Series A'.

[Assistant] SELECT pfr.project_name, pfr.investment_value, ctb.token_symbol, SUM(ctb.usd_value) AS total_cex_usd_value FROM project_fundraising_record AS pfr JOIN cex_token_balance AS ctb ON pfr.project_name = ctb.token_symbol WHERE pfr.investment_date LIKE '2023%' AND pfr.rounds_name IN ('Seed', 'Series A') GROUP BY pfr.project_name, pfr.investment_value, ctb.token_symbol;

[User] Order the results by total CEX USD value descending and limit to top 10.

[Assistant] SELECT pfr.project_name, pfr.investment_value, ctb.token_symbol, SUM(ctb.usd_value) AS total_cex_usd_value FROM project_fundraising_record AS pfr JOIN cex_token_balance AS ctb ON pfr.project_name = ctb.token_symbol WHERE pfr.investment_date LIKE '2023%' AND pfr.rounds_name IN ('Seed', 'Series A') GROUP BY pfr.project_name, pfr.investment_value, ctb.token_symbol ORDER BY total_cex_usd_value DESC LIMIT 10;

[User] I got empty results. Maybe the join condition project_name = token_symbol is too strict. Can you try a more flexible match where the token symbol is contained within the project name or vice versa, case-insensitive?

[Assistant] SELECT pfr.project_name, pfr.investment_value, ctb.token_symbol, SUM(ctb.usd_value) AS total_cex_usd_value FROM project_fundraising_record AS pfr JOIN cex_token_balance AS ctb ON LOWER(pfr.project_name) LIKE '%' || LOWER(ctb.token_symbol) || '%' OR LOWER(ctb.token_symbol) LIKE '%' || LOWER(pfr.project_name) || '%' WHERE pfr.investment_date LIKE '2023%' AND pfr.rounds_name IN ('Seed', 'Series A') GROUP BY pfr.project_name, pfr.investment_value, ctb.token_symbol ORDER BY total_cex_usd_value DESC LIMIT 10;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE project_fundraising_record ( id character varying(32) NOT NULL,  -- fundraising record id project_id character varying(32) NOT NULL, -- the invested project's id project_name character varying(128) NOT NULL, -- name of the invested project rounds_name character varying(32), -- name of the fundraising round investment_value numeric(38,14), -- amount of the fundraising in USD investment_date character varying(128), -- the date of the investment happened introduction character varying(128), -- the introduction of the invested project valuation numeric(38,14), -- the valuation of the project in USD when invested )
CREATE TABLE cex_token_balance ( snapshot_time character varying(32) NOT NULL,  -- the snapshot time of record, converted from original timestamp chain character varying(128) NOT NULL, -- the chain that the token resides address character varying(128) NOT NULL, -- the address that holds the assets, owned by a CEX exchange character varying(512) NOT NULL, -- a centralized exchange name token_address character varying(128) NOT NULL, -- token contract address token_symbol character varying(512), --token symbol balance numeric(38,10), -- token balance usd_value numeric(38,14), -- value of the token held in USD price double precision, --price of the token in USD ,PRIMARY KEY (snapshot_time, exchange, address, chain, token_address) )


[User] List all 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 SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE smart_money_token_performance ( token_address.text, token_symbol.text, pnl.numeric, net_flow.numeric, avg_cost.numeric, price.numeric, realized_ratio.numeric, roi.numeric, chain.text )


[User] For each chain, find the narrative category that has the highest total market_cap and display the chain, narrative, and that total market_cap.

[Assistant]
SELECT chain,
       narrative,
       total_cap
FROM (
  SELECT chain,
         narrative,
         SUM(market_cap) AS total_cap,
         RANK() OVER (PARTITION BY chain ORDER BY SUM(market_cap) DESC) AS rnk
  FROM token_basic_info
  GROUP BY chain, narrative
) t
WHERE rnk = 1;

[User] I received an error about window functions. Can you rewrite the query without using window functions?

[Assistant]
WITH agg AS (
  SELECT chain,
         narrative,
         SUM(market_cap) AS total_cap
  FROM token_basic_info
  GROUP BY chain, narrative
),
max_cap AS (
  SELECT chain,
         MAX(total_cap) AS max_cap
  FROM agg
  GROUP BY chain
)
SELECT a.chain,
       a.narrative,
       a.total_cap
FROM agg a
JOIN max_cap m
  ON a.chain = m.chain
 AND a.total_cap = m.max_cap;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE token_basic_info ( coin_id text, token_name text, token_symbol text, token_address text, chain text, price numeric, price_change_percentage_1h numeric, price_change_percentage_24h numeric, price_change_percentage_7d numeric, highest_price_24h numeric, lowest_price_24h numeric, market_cap numeric, market_cap_rank numeric, market_cap_change_percentage_24h text, total_volume text, narrative text, trend_rank numeric )


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

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

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE insurance.insurance_products ( product_id.text, product_name.text, product_type.text, description.text, base_premium.numeric, coverage_details.text, underwriting_rules.text, is_active.boolean, created_at.timestamp, updated_at.timestamp )
CREATE TABLE insurance.policy_beneficiaries ( beneficiary_id text PRIMARY KEY, policy_id text, customer_id text, first_name text, last_name text, relationship text, percentage_share numeric, contact_info text, added_at timestamp )


[User] Provide a count of how many peers were last seen on each distinct day recorded in the system.

[Assistant] SELECT DATE(last_seen), COUNT(*) FROM trading_platform.peers GROUP BY DATE(last_seen) ORDER BY DATE(last_seen);

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE trading_platform.users ( user_id text, username text, email text, password_hash text, created_at timestamp )
CREATE TABLE trading_platform.wallets ( wallet_id text, user_id text, address text, private_key text, created_at timestamp )
CREATE TABLE trading_platform.orders ( order_id text, user_id text, wallet_id text, asset_id text, order_type text, quantity numeric, price numeric, status text, created_at timestamp )
CREATE TABLE trading_platform.trades ( trade_id text, order_id text, buyer_id text, seller_id text, asset_id text, quantity numeric, price numeric, traded_at timestamp )
CREATE TABLE trading_platform.assets ( asset_id text, name text, symbol text, type text )
CREATE TABLE trading_platform.utxos ( utxo_id text, transaction_id text, output_index integer, address text, amount numeric, spent boolean )
CREATE TABLE trading_platform.dapps ( dapp_id text, name text, description text, url text )
CREATE TABLE trading_platform.peers ( peer_id text, ip_address text, port integer, last_seen timestamp )
CREATE TABLE trading_platform.kyc_audit ( kyc_audit_id text, user_id text, status text, reviewed_at timestamp )
CREATE TABLE trading_platform.logs ( log_id text, user_id text, action text, details text, logged_at timestamp )
CREATE TABLE trading_platform.notifications ( notification_id text, user_id text, message text, sent_at timestamp, read_at timestamp )


[User] Could you provide the total number of game sessions and the number of distinct players for each game genre? Display the genre, session count, and player count.

[Assistant] SELECT g.genre, COUNT(gs.session_id) AS session_count, COUNT(DISTINCT gs.player_id) AS player_count FROM gaming_technology.game_sessions AS gs JOIN gaming_technology.games AS g ON gs.game_id = g.game_id WHERE g.genre IS NOT NULL GROUP BY g.genre ORDER BY g.genre;

[User] Thanks. Can you modify the query to only include games that were released after the year 2020?

[Assistant] SELECT g.genre, COUNT(gs.session_id) AS session_count, COUNT(DISTINCT gs.player_id) AS player_count FROM gaming_technology.game_sessions AS gs JOIN gaming_technology.games AS g ON gs.game_id = g.game_id WHERE g.genre IS NOT NULL AND g.release_date >= '2021-01-01' GROUP BY g.genre ORDER BY g.genre;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE gaming_technology.players (
    player_id uuid NOT NULL DEFAULT gen_random_uuid(), -- unique identifier for the player
    username character varying(100) NOT NULL UNIQUE, -- player's chosen display name
    email character varying(255) NOT NULL UNIQUE, -- player's email address for login/recovery
    password_hash text NOT NULL, -- securely hashed password
    registration_date timestamp with time zone NOT NULL DEFAULT CURRENT_TIMESTAMP, -- when the player account was created
    last_login timestamp with time zone, -- timestamp of the last successful login
    country_code character(2), -- player's country (ISO 3166-1 alpha-2)
    status character varying(20) NOT NULL DEFAULT 'active', -- account status (e.g., active, banned, suspended)
    profile_data jsonb, -- flexible field for avatar url, bio, preferences etc.
    PRIMARY KEY (player_id)
)
CREATE TABLE gaming_technology.games (
    game_id uuid NOT NULL DEFAULT gen_random_uuid(), -- unique identifier for the game
    title character varying(200) NOT NULL, -- official title of the game
    developer_id uuid NOT NULL, -- FK linking to the developers table
    publisher_id uuid, -- FK linking to a potential publishers table (optional)
    genre character varying(100), -- primary genre (e.g., RPG, FPS, Strategy)
    release_date date, -- official release date
    description text, -- short description or synopsis of the game
    platform character varying(50) NOT NULL, -- primary platform (e.g., PC, PlayStation 5, Xbox Series X, Mobile)
    engine character varying(100), -- game engine used (e.g., Unreal Engine 5, Unity)
    website character varying(255), -- official website URL
    PRIMARY KEY (game_id)
    -- FOREIGN KEY (developer_id) REFERENCES gaming_technology.developers(developer_id) -- Example FK constraint
)
CREATE TABLE gaming_technology.game_sessions (
    session_id uuid NOT NULL DEFAULT gen_random_uuid(), -- unique identifier for the game session
    player_id uuid NOT NULL, -- FK linking to the players table
    game_id uuid NOT NULL, -- FK linking to the games table
    server_id uuid, -- FK linking to the servers table (nullable for single-player)
    start_time timestamp with time zone NOT NULL DEFAULT CURRENT_TIMESTAMP, -- when the session began
    end_time timestamp with time zone, -- when the session ended (null if ongoing)
    duration_seconds integer, -- calculated duration of the session in seconds
    score integer, -- player's score for the session, if applicable
    session_data jsonb, -- flexible field for session-specific info (e.g., map played, character used)
    PRIMARY KEY (session_id)
    -- FOREIGN KEY (player_id) REFERENCES gaming_technology.players(player_id),
    -- FOREIGN KEY (game_id) REFERENCES gaming_technology.games(game_id),
    -- FOREIGN KEY (server_id) REFERENCES gaming_technology.servers(server_id)
)
CREATE TABLE gaming_technology.servers (
    server_id uuid NOT NULL DEFAULT gen_random_uuid(), -- unique identifier for the game server instance
    game_id uuid NOT NULL, -- FK linking to the game this server hosts
    server_name character varying(150), -- display name for the server
    region character varying(50) NOT NULL, -- geographical region (e.g., us-east-1, eu-west-2)
    ip_address character varying(45), -- IP address (IPv4 or IPv6)
    port integer, -- network port number
    current_players integer NOT NULL DEFAULT 0, -- number of players currently connected
    max_players integer NOT NULL, -- maximum player capacity
    status character varying(30) NOT NULL DEFAULT 'offline', -- server status (e.g., online, offline, maintenance)
    last_heartbeat timestamp with time zone, -- last time the server reported its status
    PRIMARY KEY (server_id)
    -- FOREIGN KEY (game_id) REFERENCES gaming_technology.games(game_id)
)
CREATE TABLE gaming_technology.achievements (
    achievement_id uuid NOT NULL DEFAULT gen_random_uuid(), -- unique identifier for an achievement definition
    game_id uuid NOT NULL, -- FK linking to the game the achievement belongs to
    name character varying(150) NOT NULL, -- name of the achievement
    description text NOT NULL, -- how to unlock the achievement
    icon_url character varying(255), -- URL for the achievement's icon
    points integer DEFAULT 0, -- points awarded for unlocking (optional)
    hidden boolean DEFAULT false, -- whether the achievement details are hidden until unlocked
    PRIMARY KEY (achievement_id)
    -- FOREIGN KEY (game_id) REFERENCES gaming_technology.games(game_id)
)
CREATE TABLE gaming_technology.player_achievements (
    player_achievement_id uuid NOT NULL DEFAULT gen_random_uuid(), -- unique identifier for this unlock instance
    player_id uuid NOT NULL, -- FK linking to the player who unlocked it
    achievement_id uuid NOT NULL, -- FK linking to the achievement definition
    unlocked_at timestamp with time zone NOT NULL DEFAULT CURRENT_TIMESTAMP, -- when the achievement was unlocked
    PRIMARY KEY (player_achievement_id),
    UNIQUE (player_id, achievement_id) -- Ensure a player can only unlock an achievement once
    -- FOREIGN KEY (player_id) REFERENCES gaming_technology.players(player_id),
    -- FOREIGN KEY (achievement_id) REFERENCES gaming_technology.achievements(achievement_id)
)


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

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

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


[User] List the first and last names, email, and loyalty program ID of all passengers who joined after January 1, 2024.

[Assistant]
SELECT first_name, last_name, email, loyalty_program_id
FROM transportation.passengers
WHERE created_at > '2024-01-01';

[User] Include only those passengers who are enrolled in any loyalty program (loyalty_program_id is not null), and order the results by last name.

[Assistant]
SELECT first_name, last_name, email, loyalty_program_id
FROM transportation.passengers
WHERE created_at > '2024-01-01' AND loyalty_program_id IS NOT NULL
ORDER BY last_name;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE transportation.locations ( location_id text PRIMARY KEY, name text, type text, address_line1 text, city text, state_province text, postal_code text, country text, latitude numeric, longitude numeric, timezone text )
CREATE TABLE transportation.maintenance_logs ( log_id text PRIMARY KEY, vehicle_id text, service_date date, odometer_reading int, service_type text, description text, cost numeric, mechanic_name text, next_service_due_date date )
CREATE TABLE transportation.passengers ( passenger_id text PRIMARY KEY, first_name text, last_name text, email text, phone_number text, date_of_birth date, loyalty_program_id text, created_at timestamp )


[User] Show the guest's full name, reservation ID, check-in date, and status for all reservations made via 'Phone'.

[Assistant] SELECT g.first_name, g.last_name, r.reservation_id, r.check_in_date, r.status FROM hospitality_technology.reservations r JOIN hospitality_technology.guests g ON r.guest_id = g.guest_id WHERE r.booking_source = 'Phone';

[User] Now, only show reservations with a status of 'Confirmed' or 'Pending'.

[Assistant] SELECT g.first_name, g.last_name, r.reservation_id, r.check_in_date, r.status FROM hospitality_technology.reservations r JOIN hospitality_technology.guests g ON r.guest_id = g.guest_id WHERE r.booking_source = 'Phone' AND r.status IN ('Confirmed', 'Pending');

[User] Sort the results by check-in date descending and limit to the first 20.

[Assistant] SELECT g.first_name, g.last_name, r.reservation_id, r.check_in_date, r.status FROM hospitality_technology.reservations r JOIN hospitality_technology.guests g ON r.guest_id = g.guest_id WHERE r.booking_source = 'Phone' AND r.status IN ('Confirmed', 'Pending') ORDER BY r.check_in_date DESC LIMIT 20;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE hospitality_technology.guests ( guest_id character varying(64) NOT NULL, first_name character varying(100) NOT NULL, last_name character varying(100) NOT NULL, email character varying(255) UNIQUE, phone_number character varying(30), date_of_birth date, address_line1 character varying(255), city character varying(100), state_province character varying(100), postal_code character varying(20), country_code character varying(3), preferences text, loyalty_member_id character varying(64) UNIQUE, communication_consent boolean DEFAULT true, created_at timestamp with time zone NOT NULL DEFAULT current_timestamp, updated_at timestamp with time zone NOT NULL DEFAULT current_timestamp, PRIMARY KEY (guest_id) )
CREATE TABLE hospitality_technology.reservations (
    reservation_id character varying(64) NOT NULL,  -- unique identifier for the booking
    property_id character varying(64) NOT NULL, -- FK to properties table
    guest_id character varying(64) NOT NULL, -- FK to guests table (primary guest)
    room_id character varying(64), -- FK to rooms table (assigned room, might be null initially)
    room_type_id character varying(64) NOT NULL, -- FK to room_types table (booked room type)
    check_in_date date NOT NULL, -- scheduled check-in date
    check_out_date date NOT NULL, -- scheduled check-out date
    actual_check_in_ts timestamp with time zone, -- actual check-in time
    actual_check_out_ts timestamp with time zone, -- actual check-out time
    num_adults integer NOT NULL, -- number of adults
    num_children integer DEFAULT 0, -- number of children
    status character varying(50) NOT NULL, -- e.g., Pending, Confirmed, CheckedIn, CheckedOut, Cancelled, NoShow
    booking_source character varying(100), -- e.g., Website, OTA (Expedia, Booking.com), Phone, WalkIn
    rate_plan_id character varying(64), -- FK to rate_plans table (optional)
    total_amount numeric(12, 2), -- estimated or final total cost
    amount_paid numeric(12, 2) DEFAULT 0.00, -- amount already paid
    special_requests text, -- specific guest requests for this booking
    created_at timestamp with time zone NOT NULL DEFAULT current_timestamp,
    updated_at timestamp with time zone NOT NULL DEFAULT current_timestamp,
    PRIMARY KEY (reservation_id),
    FOREIGN KEY (property_id) REFERENCES hospitality_technology.properties(property_id),
    FOREIGN KEY (guest_id) REFERENCES hospitality_technology.guests(guest_id),
    FOREIGN KEY (room_id) REFERENCES hospitality_technology.rooms(room_id),
    FOREIGN KEY (room_type_id) REFERENCES hospitality_technology.room_types(room_type_id)
)
CREATE TABLE hospitality_technology.staff (
    staff_id character varying(64) NOT NULL,  -- unique identifier for the staff member
    property_id character varying(64) NOT NULL, -- FK to properties table (primary property)
    first_name character varying(100) NOT NULL,
    last_name character varying(100) NOT NULL,
    position character varying(100) NOT NULL, -- e.g., Front Desk Agent, Housekeeper, Manager, Concierge
    work_email character varying(255) UNIQUE, -- staff member's work email
    work_phone character varying(30),
    hire_date date NOT NULL,
    termination_date date, -- date employment ended (if applicable)
    is_active boolean NOT NULL DEFAULT true, -- currently employed flag
    access_level integer NOT NULL, -- permission level within systems (e.g., 1=basic, 5=admin)
    manager_id character varying(64), -- FK to staff table (self-referencing for supervisor)
    created_at timestamp with time zone NOT NULL DEFAULT current_timestamp,
    PRIMARY KEY (staff_id),
    FOREIGN KEY (property_id) REFERENCES hospitality_technology.properties(property_id),
    FOREIGN KEY (manager_id) REFERENCES hospitality_technology.staff(staff_id)
)
CREATE TABLE hospitality_technology.services ( service_id.text, property_id.text, service_name.text, description.text, category.text, price.numeric, unit.text, is_available.boolean, department.text )


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

[Assistant]
SELECT c.first_name, c.last_name, sl.city, sl.state
FROM government_services.citizens c
JOIN government_services.payments p ON c.citizen_id = p.citizen_id
JOIN government_services.employees e ON p.application_id IS NOT NULL AND e.agency_id IS NOT NULL
JOIN government_services.service_locations sl ON e.agency_id = sl.agency_id;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE government_services.citizens ( citizen_id text, national_id_number text, first_name text, last_name text, date_of_birth date, gender text, primary_address text, contact_email text, contact_phone text, registration_date timestamp, is_verified boolean )
CREATE TABLE government_services.payments ( payment_id text, application_id text, citizen_id text, service_id text, amount numeric, currency text, payment_method text, payment_provider_reference text, payment_timestamp timestamp, status text, notes text )
CREATE TABLE government_services.employees ( employee_id text, agency_id text, first_name text, last_name text, job_title text, department text, work_email text, work_phone text, hire_date date, termination_date date, access_level text, manager_employee_id text )
CREATE TABLE government_services.service_locations ( location_id text, agency_id text, location_name text, address text, city text, state text, postal_code text, latitude numeric, longitude numeric, operating_hours text, contact_phone text, is_accessible boolean )


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

[Assistant]
SELECT document_type,
       COUNT(*) AS count
FROM legal_services.documents
GROUP BY document_type
ORDER BY count DESC;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE legal_services.documents ( document_id.text, case_id.text, document_name.text, document_type.text, storage_path.text, uploaded_by_lawyer_id.text, upload_timestamp.timestamp, version.integer, description.text )


[User] What is the detailed repair history of the equipment used by the staff with staff_id 'STAFF123' during maintenance tasks?

[Assistant] I'm sorry, but I can't provide information on the detailed repair history of equipment used by staff members. The data in the maintenance_records table only includes information about maintenance tasks, such as record_id, asset_id, maintenance type, and staff_id, but does not cover equipment repair histories.

System:
You are an SQL statement expert and you can refuse the user's question if the question is not related to the table structure. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE train_station_management.maintenance_records ( record_id.text, asset_id.text, asset_type.text, maintenance_type.text, staff_id.text, start_datetime.timestamp, end_datetime.timestamp, description.text, cost.numeric, status.text )


[User] Show me the top 5 NFT collections with the highest floor price on Ethereum, along with their names and contract addresses.

[Assistant] SELECT name, contract_address, floor_price FROM nft_collections WHERE blockchain = 'ethereum' ORDER BY CAST(floor_price AS decimal) DESC LIMIT 5;

[User] Can you also include the banner image URL and filter to only show ERC721 collections?

[Assistant] SELECT name, contract_address, floor_price, banner_image_url FROM nft_collections WHERE blockchain = 'ethereum' AND erc_type = 'ERC721' ORDER BY CAST(floor_price AS decimal) DESC LIMIT 5;

[User] I think there's a typo in your query - it should be 'nft_collections' not 'nft_collections'. Also, can you join this with the nft_metadata table to include the average rarity score for these collections?

[Assistant] SELECT nc.name, nc.contract_address, nc.floor_price, nc.banner_image_url, AVG(nm.rarity_score) as avg_rarity_score FROM nft_collections nc JOIN nft_metadata nm ON nc.contract_address = nm.contract_address WHERE nc.blockchain = 'ethereum' AND nc.erc_type = 'ERC721' GROUP BY nc.name, nc.contract_address, nc.floor_price, nc.banner_image_url ORDER BY CAST(nc.floor_price AS decimal) DESC LIMIT 5;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE erc1155_approval_for_all (
    block_number bigint NOT NULL, -- Block number containing the transaction
    block_timestamp timestamp(3) NOT NULL, -- Timestamp of the block containing the transaction
    transaction_index integer NOT NULL, -- Index of the transaction within the block
    transaction_hash varchar(66) NOT NULL, -- Transaction hash
    log_index integer NOT NULL, -- Log index
    contract_address varchar(42) NOT NULL  -- Event contract address
)
CREATE TABLE erc20_balances ( block_number.bigint, contract_address.text, wallet_address.text, amount.text, pk.text )
CREATE TABLE erc20_balances_historical ( block_number bigint NOT NULL, contract_address varchar NOT NULL, wallet_address varchar NOT NULL, amount varchar NOT NULL, pk integer NOT NULL )
CREATE TABLE nft_metadata (
    blockchain varchar NOT NULL, -- blockchain fields for the functionType  in contract
    contract_address varchar NOT NULL, -- Contract address(with bloom filter)
    token_id varchar NOT NULL, -- The number of the token
    contract_name varchar NOT NULL, -- contract_name fields for the functionType  in contract
    erc_type varchar NOT NULL, -- The type of token
    amount bigint NOT NULL, -- amount fields for the functionType  in contract
    minter varchar NOT NULL, -- minter fields for the functionType  in contract
    owner varchar NOT NULL, -- owner fields for the functionType  in contract
    mint_block_number bigint NOT NULL, -- mint_block_number fields for the functionType  in contract
    mint_time bigint NOT NULL, -- mint_time fields for the functionType  in contract
    mint_transaction_hash varchar NOT NULL, -- mint_transaction_hash fields for the functionType  in contract
    mint_price varchar NOT NULL, -- mint_price fields for the functionType  in contract
    token_uri varchar NOT NULL, -- token_uri fields for the functionType  in contract
    metadata varchar NOT NULL, -- metadata fields for the functionType  in contract
    name varchar NOT NULL, -- name fields for the functionType  in contract
    image_uri varchar NOT NULL, -- image_uri fields for the functionType  in contract
    traits varchar NOT NULL, -- traits fields for the functionType  in contract
    updated_at bigint NOT NULL, -- updated_at fields for the functionType  in contract
    status varchar NOT NULL, -- status fields for the functionType  in contract
    rarity_score real NOT NULL, -- rarity_score fields for the functionType  in contract
    rarity_rank integer NOT NULL, -- rarity_rank fields for the functionType  in contract
    unique_attribute_count integer NOT NULL, -- unique_attribute_count fields for the functionType  in contract
    pk integer NOT NULL  -- Partition key for the table(floor(mint_time / 1000 / 86400 / 30))
)
CREATE TABLE nft_collections ( blockchain.text, contract_address.text, name.text, symbol.text, deploy_block_number.bigint, deploy_block_time.bigint, erc_type.text, owner.text, traits.text, description.text, slug.text, media_info.text, image_url.text, banner_image_url.text, updated_at.bigint, banner.text, token_count.bigint, floor_price.text, floor_price_symbol.text, floor_price_contract.text, pk.integer )
CREATE TABLE token_prices ( uuid varchar(36) NOT NULL, blockchain varchar(36) NOT NULL, address varchar(42) NOT NULL, decimals bigint NOT NULL, symbol varchar(36) NOT NULL, price real NOT NULL, timestamp timestamp(6) NOT NULL )
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_info ( block_timestamp timestamp(3) NOT NULL, block_number bigint NOT NULL, tx_index integer NOT NULL, tx_hash varchar(66) NOT NULL, tick varchar NOT NULL, max_supply decimal(38,0) NOT NULL, lim decimal(38,0) NOT NULL, wlim decimal(38,0) NOT NULL, dec integer NOT NULL, creator varchar(42) NOT NULL )
CREATE TABLE 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_info_bitcoin ( block_timestamp timestamp, block_number bigint, tx_index integer, tx_hash varchar, tick varchar, max_supply decimal, lim decimal, wlim decimal, dec integer, creator varchar )
CREATE TABLE token_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] Find all medical records with a vital sign for temperature above 38°C. Show the record ID and record date.

[Assistant]
SELECT record_id, record_date
FROM healthcare.medical_records
WHERE (vitals ->> 'temperature')::numeric > 38;

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


[User] Which route numbers connect locations with a distance less than 80 km and more than 5 words in their description? Include the route type in the results.

[Assistant] SELECT route_number, type FROM transportation.routes WHERE distance_km < 80 AND array_length(regexp_split_to_array(description, '\s+'), 1) > 5;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE transportation.routes ( route_id text, route_number text, description text, origin_location_id text, destination_location_id text, distance_km numeric, estimated_duration_minutes integer, type text )


[User] List all invoices that were paid within 7 days of their issue date. Show invoice number, issue date, payment date, and total amount.

[Assistant] SELECT invoice_number, issue_date, payment_date, total_amount FROM legal_services.invoices WHERE status = 'Paid' AND payment_date IS NOT NULL AND (payment_date::DATE - issue_date) <= 7;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE legal_services.lawyers ( lawyer_id.text, first_name.text, last_name.text, bar_number.text, firm_id.text, email.text, phone.text, specialization.text, hire_date.timestamp, is_partner.boolean )
CREATE TABLE legal_services.invoices ( invoice_id text, invoice_number text, client_id text, case_id text, issue_date date, due_date date, total_amount numeric, amount_paid numeric, status text, payment_date timestamp, notes text, created_at timestamp )


[User] List all wallet addresses that have unspent UTXOs with amounts greater than 100, along with the total unspent amount for each address.

[Assistant] SELECT w.address, SUM(u.amount) AS total_unspent FROM trading_platform.wallets w JOIN trading_platform.utxos u ON w.address = u.address WHERE u.spent = false AND u.amount > 100 GROUP BY w.address;

[User] Now modify the query to only include wallets created in the last year.

[Assistant] SELECT w.address, SUM(u.amount) AS total_unspent FROM trading_platform.wallets w JOIN trading_platform.utxos u ON w.address = u.address WHERE u.spent = false AND u.amount > 100 AND w.created_at >= NOW() - INTERVAL '1 year' GROUP BY w.address;

[User] I notice the query has a typo in 'INTERVAL'. Also, can you include the user's email address in the results?

[Assistant] SELECT w.address, u.email, SUM(ut.amount) AS total_unspent FROM trading_platform.wallets w JOIN trading_platform.users u ON w.user_id = u.user_id JOIN trading_platform.utxos ut ON w.address = ut.address WHERE ut.spent = false AND ut.amount > 100 AND w.created_at >= NOW() - INTERVAL '1 year' GROUP BY w.address, u.email;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE trading_platform.users ( user_id text PRIMARY KEY, username text, email text, password_hash text, created_at timestamp )
CREATE TABLE trading_platform.wallets ( wallet_id text PRIMARY KEY, user_id text, address text, private_key text, created_at timestamp )
CREATE TABLE trading_platform.orders ( order_id text PRIMARY KEY, user_id text, wallet_id text, asset_id text, order_type text, quantity numeric, price numeric, status text, created_at timestamp )
CREATE TABLE trading_platform.trades ( trade_id text PRIMARY KEY, order_id text, buyer_id text, seller_id text, asset_id text, quantity numeric, price numeric, traded_at timestamp )
CREATE TABLE trading_platform.utxos ( utxo_id text PRIMARY KEY, transaction_id text, output_index int, address text, amount numeric, spent boolean )
CREATE TABLE trading_platform.dapps ( dapp_id text PRIMARY KEY, name text, description text, url text )
CREATE TABLE trading_platform.metadata ( metadata_id text PRIMARY KEY, asset_id text, key text, value text )
CREATE TABLE trading_platform.notifications ( notification_id text PRIMARY KEY, user_id text, message text, sent_at timestamp, read_at timestamp )


[User] Find all users whose usernames contain numbers and have email addresses from either Gmail or Yahoo.

[Assistant] SELECT user_id, username, email FROM blockchain.users WHERE username ~ '[0-9]' AND (email LIKE '%@gmail.com' OR email LIKE '%@yahoo.com');

[User] Now, order these results by username length in descending order.

[Assistant] SELECT user_id, username, email FROM blockchain.users WHERE username ~ '[0-9]' AND (email LIKE '%@gmail.com' OR email LIKE '%@yahoo.com') ORDER BY LENGTH(username) DESC;

[User] Can you modify this to only show the top 5 longest usernames?

[Assistant] SELECT user_id, username, email FROM blockchain.users WHERE username ~ '[0-9]' AND (email LIKE '%@gmail.com' OR email LIKE '%@yahoo.com') ORDER BY LENGTH(username) DESC LIMIT 5;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE blockchain.nodes ( node_id text, ip_address text, port integer, last_seen timestamp )
CREATE TABLE blockchain.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
    PRIMARY KEY (user_id)
)


[User] Show me pairs of a block and its previous block where the previous block's difficulty was greater than 100000. Include details for both blocks.

[Assistant] SELECT t1.block_id AS current_block_id, t2.block_id AS previous_block_id, t1.timestamp AS current_timestamp, t2.timestamp AS previous_timestamp, t1.difficulty AS current_difficulty, t2.difficulty AS previous_difficulty FROM blockchain.blocks AS t1 JOIN blockchain.blocks AS t2 ON t1.previous_block_id = t2.block_id WHERE t2.difficulty > 100000;

[User] Okay, now filter those results to only include pairs where the time difference between the current block and its predecessor is less than 600 seconds.

[Assistant] SELECT t1.block_id AS current_block_id, t2.block_id AS previous_block_id, t1.timestamp AS current_timestamp, t2.timestamp AS previous_timestamp, t1.difficulty AS current_difficulty, t2.difficulty AS previous_difficulty FROM blockchain.blocks AS t1 JOIN blockchain.blocks AS t2 ON t1.previous_block_id = t2.block_id WHERE t2.difficulty > 100000 AND EXTRACT(EPOCH FROM (t1.timestamp - t2.timestamp)) < 600;

[User] Further refine the list to only include blocks mined in October 2023.

[Assistant] SELECT t1.block_id AS current_block_id, t2.block_id AS previous_block_id, t1.timestamp AS current_timestamp, t2.timestamp AS previous_timestamp, t1.difficulty AS current_difficulty, t2.difficulty AS previous_difficulty FROM blockchain.blocks AS t1 JOIN blockchain.blocks AS t2 ON t1.previous_block_id = t2.block_id WHERE t2.difficulty > 100000 AND EXTRACT(EPOCH FROM (t1.timestamp - t2.timestamp)) < 600 AND t1.timestamp >= '2023-10-01' AND t1.timestamp < '2023-11-01';

[User] Finally, from this filtered list, only show pairs where the current block's difficulty is less than the previous block's difficulty.

[Assistant] SELECT t1.block_id AS current_block_id, t2.block_id AS previous_block_id, t1.timestamp AS current_timestamp, t2.timestamp AS previous_timestamp, t1.difficulty AS current_difficulty, t2.difficulty AS previous_difficulty FROM blockchain.blocks AS t1 JOIN blockchain.blocks AS t2 ON t1.previous_block_id = t2.block_id WHERE t2.difficulty > 100000 AND EXTRACT(EPOCH FROM (t1.timestamp - t2.timestamp)) < 600 AND t1.timestamp >= '2023-10-01' AND t1.timestamp < '2023-11-01' AND t1.difficulty < t2.difficulty;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE blockchain.blocks ( block_id character varying(64) NOT NULL, previous_block_id character varying(64), timestamp timestamp NOT NULL, nonce integer NOT NULL, merkle_root character varying(128) NOT NULL, difficulty integer NOT NULL, PRIMARY KEY (block_id) )


[User] Show all users whose full name starts with 'A' and who have updated their profile in June 2024. Please include their usernames and updated_at timestamps.

[Assistant] SELECT username, updated_at FROM social_media.users WHERE full_name ILIKE 'A%' AND EXTRACT(YEAR FROM updated_at) = 2024 AND EXTRACT(MONTH FROM updated_at) = 6;

[User] I also want to know which of them have a verified profile. Can you add the verification status to the results?

[Assistant] SELECT username, updated_at, is_verified FROM social_media.users WHERE full_name ILIKE 'A%' AND EXTRACT(YEAR FROM updated_at) = 2024 AND EXTRACT(MONTH FROM updated_at) = 6;

[User] Now, please only show the users who are verified.

[Assistant] SELECT username, updated_at FROM social_media.users WHERE full_name ILIKE 'A%' AND EXTRACT(YEAR FROM updated_at) = 2024 AND EXTRACT(MONTH FROM updated_at) = 6 AND is_verified = true;

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


[User] What are the maintenance costs for a specific aircraft model like the Airbus A320?

[Assistant] I'm sorry, but I don't have access to data regarding maintenance costs for specific aircraft models such as the Airbus A320. The information in the database is limited to details like model name, manufacturer, passenger capacity, and technical specifications. For maintenance cost information, you may need to consult with the manufacturer or a maintenance service provider.

System:
You are an SQL statement expert and you can refuse the user's question if the question is not related to the table structure. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE manufacturing.aircraft_models ( model_id character varying(64) NOT NULL, model_name character varying(128) NOT NULL, manufacturer character varying(128) NOT NULL, passenger_capacity integer, max_range_km integer, engine_type character varying(100), wingspan_m numeric(6,2), status character varying(50) NOT NULL, first_flight_date date, PRIMARY KEY (model_id) )


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

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

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


[User] Find the diagnosis code and description for all non-chronic diagnoses for patient 'patient_789' made by doctor 'doctor_abc'.

[Assistant] SELECT diagnosis_code, description FROM healthcare.diagnoses WHERE patient_id = 'patient_789' AND doctor_id = 'doctor_abc' AND is_chronic = false;

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


[User] Show me the top 5 projects by valuation that completed fundraising rounds in the last 12 months, along with their token symbol and price from the token_basic_info table.

[Assistant] SELECT pfr.project_name, pfr.valuation, tbi.token_symbol, tbi.price FROM project_fundraising_record pfr LEFT JOIN token_basic_info tbi ON pfr.project_name = tbi.token_name WHERE pfr.investment_date >= DATE_SUB(CURRENT_DATE, INTERVAL 12 MONTH) ORDER BY pfr.valuation DESC LIMIT 5;

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

[Assistant] SELECT pfr.project_name, pfr.valuation, tbi.token_symbol, tbi.price, tbi.total_volume FROM project_fundraising_record pfr LEFT JOIN token_basic_info tbi ON pfr.project_name = tbi.token_name WHERE pfr.investment_date >= DATE_SUB(CURRENT_DATE, INTERVAL 12 MONTH) AND pfr.valuation > 100000000 ORDER BY pfr.valuation DESC LIMIT 5;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
 "CREATE TABLE project_fundraising_record (",
    "id character varying(32) NOT NULL,  -- fundraising record id",
    "project_id character varying(32) NOT NULL, -- the invested project's id",
    "project_name character varying(128) NOT NULL, -- name of the invested project",
    "rounds_name character varying(32), -- name of the fundraising round",
    "investment_value numeric(38,14), -- amount of the fundraising in USD",
    "investment_date character varying(128), -- the date of the investment happened",
    "introduction character varying(128), -- the introduction of the invested project",
    "valuation numeric(38,14), -- the valuation of the project in USD when invested",

CREATE TABLE token_basic_info ( coin_id character varying(100) NOT NULL, -- the id of the token token_name character varying(100) NOT NULL, -- the token's name token_symbol character varying(100) NOT NULL, -- the token's symbol token_address character varying(100) NOT NULL, -- the token's address chain text, -- the chain that the token resides price double precision, -- the current price of the token price_change_percentage_1h double precision, -- change in value divided by the absolute price value of the original token price in 1 hour price_change_percentage_24h double precision, -- change in value divided by the absolute price value of the original token price in 24 hours price_change_percentage_7d double precision, -- change in value divided by the absolute price value of the original token price in 7 days highest_price_24h double precision, -- the highest price of the token in 24 hours lowest_price_24h double precision,  -- the lowest price of the token in 24 hours market_cap double precision, -- the market cap of the token market_cap_rank bigint, -- the rank of the token market cap in desc market_cap_change_percentage_24h text, -- the percentage of market cap changes in 24 hours total_volume text, -- the trade volum of the token both in decentralized exchange(DEX) and centralized exchange(CEX) narrative text, -- the category or narrative of the token trend_rank biging, -- the trending rank of the token, value 1 expresses the most popular token. ,PRIMARY KEY (coin_id, chain) )
CREATE TABLE narrative_info ( narrative character varying(512) NOT NULL, -- the id of narrative top_3_coins text, -- the top 3 tokens in the narrative price_change_percentage_1h double precision, -- change in value divided by the absolute price value of the original token price in 1 hour in the narrative price_change_percentage_24h double precision, -- change in value divided by the absolute price value of the original token price in 24 hours in the narrative price_change_percentage_7d double precision, -- change in value divided by the absolute price value of the original token price in 7 days in the narrative market_cap double precision, -- the market cap of the narrative volume_24h double precision, -- the trade volume of the narrative trend_rank bigint, -- the trending rank of the narrative, value 1 expresses the most popular narrative token_num bigint, -- total token number in the narrative ,PRIMARY KEY (narrative) )
CREATE TABLE token_dexpool_info ( pair_address character varying(512) NOT NULL, token_name character varying(100) NOT NULL, token_symbol character varying(100) NOT NULL, chain text, price double precision, price_change_percentage_1h double precision, price_change_percentage_6h double precision, price_change_percentage_24h double precision, makers_24h double precision, volume_24h double precision, liquidity double precision, market_cap double precision, trend_rank bigint )
CREATE TABLE smart_money_profit ( address character varying(100) NOT NULL, rank INT, profit numeric(38,6), roi numeric(38,2), realized_ratio numeric(38,2), most_profit_token character varying(100), last_trade_time character varying(100), chain character varying(100) )
  "CREATE TABLE smart_money_token_performance (",
    "token_address character varying(100) NOT NULL, -- the token's address",
    "token_symbol character varying(100), -- the tokens's symbol",
    "pnl numeric(38,2), -- the profit users made on this token",
    "net_flow numeric(38,2), -- the netflow of the token, means the money user spent minus the the money user sold of this token",
    "avg_cost numeric(38,16), -- the average cost price of user spent on this token",
    "price double precision, -- the current price of the token",
    "realized_ratio numeric(10,2), -- the ratio user sold of the token",
    "roi numeric(10,2), -- the roi users made of this token",
    "chain character varying(100), -- the chain that the token resides",
    "PRIMARY KEY (token_address, chain));",

  "CREATE TABLE smart_money_token_inflow (",
    "token_address character varying(100) NOT NULL, -- the token's address",
    "token_symbol character varying(100), -- the tokens's symbol",
    "token_amount numeric(38,2), -- the absolute value of the amount if user bought minus  the amount user sold of this token",
    "usd_value numeric(38,2), -- the absolute usd value of the bought token minus sold token",
    "avg_price numeric(38,6), -- the average cost price of user spent on this token",
    "type int, -- the direction of the trade on this token. 1 means buying, 2 means selling",
    "address_amount integer, -- the amount of the user bought this token",
    "narrative character varying(100), -- the category or narrative of the token",
    "chain character varying(100), -- the chain that the token resides",
    ",PRIMARY KEY (token_address, chain)",


[User] Provide the contract ID, creator address, and timestamp for all smart contracts created between January 1st, 2022, and December 31st, 2024.

[Assistant] SELECT contract_id, creator_address, timestamp FROM blockchain.smart_contracts WHERE timestamp BETWEEN '2022-01-01' AND '2024-12-31';

[User] Okay, now filter that list to only show the contracts where the code contains the word 'transfer'.

[Assistant] SELECT contract_id, creator_address, timestamp FROM blockchain.smart_contracts WHERE timestamp BETWEEN '2022-01-01' AND '2024-12-31' AND code LIKE '%transfer%';

[User] Finally, from the filtered results, I only want to see the contracts created by '0xFEDCBA9876543210FEDCBA9876543210FEDCBA98'.

[Assistant] SELECT contract_id, creator_address, timestamp FROM blockchain.smart_contracts WHERE timestamp BETWEEN '2022-01-01' AND '2024-12-31' AND code LIKE '%transfer%' AND creator_address = '0xFEDCBA9876543210FEDCBA9876543210FEDCBA98';

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 blockchain.smart_contracts ( contract_id.text, creator_address.text, code.text, timestamp.timestamp )


[User] List all premium payments with a due date in March 2024.

[Assistant] SELECT * FROM insurance.premium_payments WHERE due_date >= '2024-03-01' AND due_date <= '2024-03-31';

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE insurance.premium_payments ( payment_id text PRIMARY KEY, policy_id text, customer_id text, payment_date timestamp, amount_paid numeric, payment_method text, transaction_reference text, due_date date, payment_period_start date, payment_period_end date, status text )


[User] Find all pairs of users who signed up on the same day. Return both usernames and the signup date.

[Assistant]
SELECT u1.username AS user1, u2.username AS user2, DATE(u1.created_at) AS signup_date
FROM social_media.users u1
JOIN social_media.users u2
  ON DATE(u1.created_at) = DATE(u2.created_at)
  AND u1.user_id < u2.user_id;

[User] Include only pairs where the signup date is after '2024-01-01'.

[Assistant]
SELECT u1.username AS user1, u2.username AS user2, DATE(u1.created_at) AS signup_date
FROM social_media.users u1
JOIN social_media.users u2
  ON DATE(u1.created_at) = DATE(u2.created_at)
  AND u1.user_id < u2.user_id
WHERE DATE(u1.created_at) > '2024-01-01';

[User] Order the results by signup date descending.

[Assistant]
SELECT u1.username AS user1, u2.username AS user2, DATE(u1.created_at) AS signup_date
FROM social_media.users u1
JOIN social_media.users u2
  ON DATE(u1.created_at) = DATE(u2.created_at)
  AND u1.user_id < u2.user_id
WHERE DATE(u1.created_at) > '2024-01-01'
ORDER BY signup_date DESC;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE social_media.users ( user_id text PRIMARY KEY, 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 bool )


[User] Show me the user ID, username, and email for all users.

[Assistant] SELECT user_id, username, email FROM blockchain.users;

[User] Now, only show the users whose username starts with 'alpha'.

[Assistant] SELECT user_id, username, email FROM blockchain.users WHERE username LIKE 'alpha%';

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


[User] List clients who have appointments with lawyers from law firms founded before the year 2010. Show the client's first name, last name, the appointment subject, the lawyer's first name, last name, and the firm name.

[Assistant] SELECT T1.first_name, T1.last_name, T2.subject, T3.first_name, T3.last_name, T4.firm_name FROM legal_services.clients AS T1 JOIN legal_services.appointments AS T2 ON T1.client_id = T2.client_id JOIN legal_services.lawyers AS T3 ON T2.lawyer_id = T3.lawyer_id JOIN legal_services.law_firms AS T4 ON T3.firm_id = T4.firm_id WHERE T4.founded_date < '2010-01-01';

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE legal_services.clients ( client_id text PRIMARY KEY, first_name text, last_name text, company_name text, email text UNIQUE, phone text, address text, date_registered timestamp, status text )
CREATE TABLE legal_services.law_firms ( firm_id text PRIMARY KEY, firm_name text, address text, phone text, website text, founded_date date, managing_partner_id text )
CREATE TABLE legal_services.cases ( case_id.text, case_number.text, case_name.text, client_id.text, lead_lawyer_id.text, case_type.text, status.text, date_opened.timestamp, date_closed.timestamp, description.text, court_jurisdiction.text )
CREATE TABLE legal_services.documents (
    document_id character varying(64) NOT NULL,  -- unique identifier for the document
    case_id character varying(64) NOT NULL, -- FK to cases table
    document_name character varying(255) NOT NULL, -- name of the document file
    document_type character varying(100), -- e.g., Pleading, Contract, Evidence, Correspondence
    storage_path text NOT NULL, -- path or reference to the document storage location
    uploaded_by_lawyer_id character varying(64), -- FK to lawyers table (who uploaded it)
    upload_timestamp timestamp NOT NULL, -- time the document was uploaded
    version integer DEFAULT 1, -- document version number
    description text, -- brief description or notes about the document
    PRIMARY KEY (document_id)
)
CREATE TABLE legal_services.appointments (
    appointment_id character varying(64) NOT NULL, -- unique identifier for the appointment
    client_id character varying(64) NOT NULL, -- FK to clients table
    lawyer_id character varying(64) NOT NULL, -- FK to lawyers table
    case_id character varying(64), -- FK to cases table (optional, if related to a specific case)
    start_time timestamp NOT NULL, -- scheduled start date and time
    end_time timestamp NOT NULL, -- scheduled end date and time
    location text, -- location of the meeting (address or virtual link)
    subject character varying(255), -- subject or purpose of the appointment
    notes text, -- additional notes for the appointment
    status character varying(50) NOT NULL, -- e.g., Scheduled, Completed, Canceled, Rescheduled
    created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
    PRIMARY KEY (appointment_id)
)


[User] Find pairs of developers located in the same country but founded in different years.

[Assistant]
SELECT d1.name AS developer1, d2.name AS developer2, d1.country, d1.founded_year, d2.founded_year
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] Only include pairs where the difference in founded_year is greater than 5 years.

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

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE gaming_technology.developers ( developer_id uuid, name text, country text, founded_year integer, website text, created_at timestamp with time zone )


[User] List all reservations made by guests from 'US', showing the reservation ID, guest first name, last name, and the property name.

[Assistant] SELECT T1.reservation_id, T2.first_name, T2.last_name, T3.property_name FROM hospitality_technology.reservations AS T1 JOIN hospitality_technology.guests AS T2 ON T1.guest_id = T2.guest_id JOIN hospitality_technology.properties AS T3 ON T1.property_id = T3.property_id WHERE T2.country_code = 'US';

[User] Only show reservations with status 'Confirmed'.

[Assistant] SELECT T1.reservation_id, T2.first_name, T2.last_name, T3.property_name FROM hospitality_technology.reservations AS T1 JOIN hospitality_technology.guests AS T2 ON T1.guest_id = T2.guest_id JOIN hospitality_technology.properties AS T3 ON T1.property_id = T3.property_id WHERE T2.country_code = 'US' AND T1.status = 'Confirmed';

[User] Also include the check-in and check-out dates, and order by check-in date descending.

[Assistant] SELECT T1.reservation_id, T2.first_name, T2.last_name, T3.property_name, T1.check_in_date, T1.check_out_date FROM hospitality_technology.reservations AS T1 JOIN hospitality_technology.guests AS T2 ON T1.guest_id = T2.guest_id JOIN hospitality_technology.properties AS T3 ON T1.property_id = T3.property_id WHERE T2.country_code = 'US' AND T1.status = 'Confirmed' ORDER BY T1.check_in_date DESC;

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


[User] Find tokens that have a positive price change percentage over the last 1 hour, 6 hours, and 24 hours. Display their symbol and chain.

[Assistant] SELECT token_symbol, chain FROM token_dexpool_info WHERE price_change_percentage_1h > 0 AND price_change_percentage_6h > 0 AND price_change_percentage_24h > 0;

[User] Only show results for chains where the average trend rank is better than 5 (lower value indicates higher popularity).

[Assistant] SELECT token_symbol, chain FROM token_dexpool_info WHERE price_change_percentage_1h > 0 AND price_change_percentage_6h > 0 AND price_change_percentage_24h > 0 AND chain IN (SELECT chain FROM token_dexpool_info GROUP BY chain HAVING AVG(trend_rank) < 5);

[User] Order the results by the 24-hour price change percentage in descending order.

[Assistant] SELECT token_symbol, chain, price_change_percentage_24h FROM token_dexpool_info WHERE price_change_percentage_1h > 0 AND price_change_percentage_6h > 0 AND price_change_percentage_24h > 0 AND chain IN (SELECT chain FROM token_dexpool_info GROUP BY chain HAVING AVG(trend_rank) < 5) ORDER BY price_change_percentage_24h DESC;

[User] Limit the result to the top 20 tokens.

[Assistant] SELECT token_symbol, chain, price_change_percentage_24h FROM token_dexpool_info WHERE price_change_percentage_1h > 0 AND price_change_percentage_6h > 0 AND price_change_percentage_24h > 0 AND chain IN (SELECT chain FROM token_dexpool_info GROUP BY chain HAVING AVG(trend_rank) < 5) ORDER BY price_change_percentage_24h DESC LIMIT 20;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE token_dexpool_info ( pair_address character varying(512) NOT NULL, -- the id of dexpool token_name character varying(100) NOT NULL, -- the name of the token in the dexpool token_symbol character varying(100) NOT NULL, -- the token's symbol chain text, -- the chain that the dexpool resides price double precision, -- the current price of the token price_change_percentage_1h double precision, -- change in value divided by the absolute price value of the original token price in 1 hour price_change_percentage_6h double precision, -- change in value divided by the absolute price value of the original token price in 6 hours price_change_percentage_24h double precision, -- change in value divided by the absolute price value of the original token price in 24 hours makers_24h double precision, -- the makers of the dex pool in 24 hours volume_24h double precision, -- the trade volume of the dex pool in 24 hours liquidity double precision, -- the liquidity of the dex pool market_cap double precision, -- the market cap of the token trend_rank bigint, -- the rank of token in the dex pool of recent trending, value 1 expresses the most popular token. ,PRIMARY KEY (pair_address, chain) )


[User] I want to list each public post along with its content, the author's username, and the total number of comments it has received. Order the results by comment count descending.

[Assistant]
SELECT p.post_id,
       u.username,
       p.content,
       COUNT(c.comment_id) AS comment_count
FROM social_media.posts AS p
JOIN social_media.users AS u
  ON p.user_id = u.user_id
LEFT JOIN social_media.comments AS c
  ON p.post_id = c.post_id
WHERE p.visibility = 'public'
GROUP BY p.post_id, u.username, p.content
ORDER BY comment_count DESC;

[User] Actually, can you filter this to only include posts created after '2024-01-01' that have at least 5 comments?

[Assistant]
SELECT p.post_id,
       u.username,
       p.content,
       COUNT(c.comment_id) AS comment_count
FROM social_media.posts AS p
JOIN social_media.users AS u
  ON p.user_id = u.user_id
LEFT JOIN social_media.comments AS c
  ON p.post_id = c.post_id
WHERE p.visibility = 'public'
  AND p.created_at > '2024-01-01'
GROUP BY p.post_id, u.username, p.content
HAVING COUNT(c.comment_id) >= 5
ORDER BY comment_count DESC;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE 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.text, post_id.text, user_id.text, parent_comment_id.text, content.text, created_at.timestamp, updated_at.timestamp )
CREATE TABLE social_media.likes ( like_id text PRIMARY KEY, user_id text, post_id text, comment_id text, created_at timestamp )
CREATE TABLE social_media.follows (
    follow_id character varying(64) NOT NULL, -- unique identifier for the follow relationship
    follower_user_id character varying(64) NOT NULL, -- identifier of the user who is following (FK to users.user_id)
    following_user_id character varying(64) NOT NULL, -- identifier of the user being followed (FK to users.user_id)
    created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, -- timestamp of when the follow started
    PRIMARY KEY (follow_id),
    CONSTRAINT unique_follow UNIQUE (follower_user_id, following_user_id) -- prevent duplicate follows
)
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 text PRIMARY KEY, post_id text, hashtag_id text )
CREATE TABLE social_media.conversations ( conversation_id.text, created_at.timestamp, last_message_at.timestamp, is_group_chat.boolean, group_name.text )
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.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] Show each user_id along with the total number of wallets they own.

[Assistant]
SELECT user_id, COUNT(*) AS wallet_count
FROM blockchain.wallets
GROUP BY user_id;

[User] Only include users who have more than 1 wallet.

[Assistant]
SELECT user_id, COUNT(*) AS wallet_count
FROM blockchain.wallets
GROUP BY user_id
HAVING COUNT(*) > 1;

[User] And order the output by wallet_count descending.

[Assistant]
SELECT user_id, COUNT(*) AS wallet_count
FROM blockchain.wallets
GROUP BY user_id
HAVING COUNT(*) > 1
ORDER BY wallet_count DESC;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE blockchain.wallets ( wallet_id character varying(64) NOT NULL, user_id character varying(64) NOT NULL, address_id character varying(128) NOT NULL, private_key text NOT NULL, PRIMARY KEY (wallet_id) )


[User] Find all patients who have insurance plans with group numbers, showing their patient IDs and the count of such plans per patient, ordered by count in descending order.

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

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