[User] Which games have achievements where the points value is exactly 0? List the game title and the achievement name.

[Assistant]
SELECT g.title AS game_title, a.name AS achievement_name
FROM gaming_technology.achievements a
JOIN gaming_technology.games g ON a.game_id = g.game_id
WHERE a.points = 0;

[User] Show also the achievement's description and whether it is hidden.

[Assistant]
SELECT g.title AS game_title, a.name AS achievement_name, a.description, a.hidden
FROM gaming_technology.achievements a
JOIN gaming_technology.games g ON a.game_id = g.game_id
WHERE a.points = 0;

[User] Only show achievements released in games before 2020.

[Assistant]
SELECT g.title AS game_title, a.name AS achievement_name, a.description, a.hidden
FROM gaming_technology.achievements a
JOIN gaming_technology.games g ON a.game_id = g.game_id
WHERE a.points = 0 AND g.release_date < '2020-01-01';

[User] Sort the results by game_title ascending, then achievement_name ascending.

[Assistant]
SELECT g.title AS game_title, a.name AS achievement_name, a.description, a.hidden
FROM gaming_technology.achievements a
JOIN gaming_technology.games g ON a.game_id = g.game_id
WHERE a.points = 0 AND g.release_date < '2020-01-01'
ORDER BY g.title ASC, a.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 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)
)
CREATE TABLE gaming_technology.in_game_items (
    item_id uuid NOT NULL DEFAULT gen_random_uuid(), -- unique identifier for the item definition
    game_id uuid NOT NULL, -- FK linking to the game this item belongs to
    item_name character varying(150) NOT NULL, -- name of the item
    item_type character varying(50) NOT NULL, -- type (e.g., Cosmetic, Consumable, Weapon, Armor)
    description text, -- description of the item
    rarity character varying(30), -- item rarity (e.g., Common, Rare, Epic, Legendary)
    cost_currency character varying(10), -- currency code if purchasable (e.g., USD, EUR, GOLD)
    cost_amount numeric(12, 2), -- price if purchasable
    attributes jsonb, -- flexible field for item stats or properties
    PRIMARY KEY (item_id)
    -- FOREIGN KEY (game_id) REFERENCES gaming_technology.games(game_id)
)
CREATE TABLE gaming_technology.player_inventory (
    inventory_id uuid NOT NULL DEFAULT gen_random_uuid(), -- unique identifier for an inventory entry
    player_id uuid NOT NULL, -- FK linking to the player owning the item
    item_id uuid NOT NULL, -- FK linking to the item definition
    quantity integer NOT NULL DEFAULT 1, -- number of items held (for stackable items)
    acquired_at timestamp with time zone NOT NULL DEFAULT CURRENT_TIMESTAMP, -- when the item was acquired
    instance_data jsonb, -- data specific to this instance (e.g., weapon mods, durability)
    PRIMARY KEY (inventory_id),
    -- Optional unique constraint if items are non-stackable or unique instances
    -- UNIQUE (player_id, item_id) -- Use if quantity is always 1
    -- FOREIGN KEY (player_id) REFERENCES gaming_technology.players(player_id),
    -- FOREIGN KEY (item_id) REFERENCES gaming_technology.in_game_items(item_id)
)


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

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

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

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

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

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

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE healthcare.patient_insurance (
    patient_insurance_id character varying(64) NOT NULL, -- unique identifier for this patient-plan link
    patient_id character varying(64) NOT NULL, -- FK to patients table
    plan_id character varying(64) NOT NULL, -- FK to insurance_plans table
    policy_number character varying(100) NOT NULL, -- patient's policy number
    group_number character varying(100), -- group number, if applicable
    subscriber_name character varying(200), -- name of the primary policy holder
    effective_date date NOT NULL, -- date the coverage begins
    expiration_date date, -- date the coverage ends (if known)
    is_primary boolean NOT NULL DEFAULT true, -- indicates if this is the primary insurance
    PRIMARY KEY (patient_insurance_id),
    UNIQUE (patient_id, plan_id, policy_number) -- ensure a patient doesn't have the same policy twice
)


[User] List each insurance product's name and type, along with the number of active policies and the total premium_amount collected for those policies. Only include products that have at least one active policy.

[Assistant]
SELECT p.product_name,
       p.product_type,
       COUNT(pl.policy_id) AS active_policy_count,
       SUM(pl.premium_amount) AS total_premium
FROM insurance.insurance_products p
JOIN insurance.policies pl ON p.product_id = pl.product_id
WHERE pl.status = 'Active'
GROUP BY p.product_name, p.product_type
HAVING COUNT(pl.policy_id) > 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 insurance.customers ( customer_id text PRIMARY KEY, first_name text, last_name text, date_of_birth date, ssn_hash text, address_line1 text, address_line2 text, city text, state text, zip_code text, country text, phone_number text, email text, created_at timestamp, updated_at timestamp, status text )
CREATE TABLE insurance.policies ( policy_id text PRIMARY KEY, customer_id text, product_id text, agent_id text, policy_number text, start_date date, end_date date, premium_amount numeric, coverage_limit numeric, deductible numeric, status text, issued_at timestamp, cancellation_date date, cancellation_reason text )
CREATE TABLE insurance.claims ( claim_id text PRIMARY KEY, policy_id text, customer_id text, incident_date timestamp, reported_date timestamp, description text, estimated_loss numeric, status text, settlement_amount numeric, settlement_date date, claim_handler_id text, police_report_number text )
CREATE TABLE insurance.insurance_products ( product_id text PRIMARY KEY, product_name text, product_type text, description text, base_premium numeric, coverage_details text, underwriting_rules text, is_active boolean, created_at timestamp, updated_at timestamp )
CREATE TABLE insurance.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 )
CREATE TABLE insurance.claim_documents ( document_id text PRIMARY KEY, claim_id text, document_type text, file_name text, file_path text, file_size_bytes int, mime_type text, uploaded_by text, uploaded_at timestamp, description text )
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] Which routes have their origin and destination in the same city? Show the route number, description, and the origin and destination location IDs.

[Assistant]
SELECT r.route_number, r.description, r.origin_location_id, r.destination_location_id
FROM transportation.routes r
JOIN transportation.routes r2 ON r.origin_location_id = r2.destination_location_id AND r.route_id = r2.route_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 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] 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] 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] Provide a summary for each user, showing their associated KYC status and the total number of UTXOs connected to them.

[Assistant] SELECT kyc.user_id, kyc.status, COUNT(u.utxo_id) AS utxo_count FROM trading_platform.kyc_audit kyc JOIN trading_platform.utxos u ON kyc.user_id = u.user_id GROUP BY kyc.user_id, kyc.status;

[User] Could you filter the summary to include only users whose status is 'pending' or 'rejected'?

[Assistant] SELECT kyc.user_id, kyc.status, COUNT(u.utxo_id) AS utxo_count FROM trading_platform.kyc_audit kyc JOIN trading_platform.utxos u ON kyc.user_id = u.user_id WHERE kyc.status IN ('pending', 'rejected') GROUP BY kyc.user_id, kyc.status;

[User] Also, limit the results to users with a count of more than 5 UTXOs.

[Assistant] SELECT kyc.user_id, kyc.status, COUNT(u.utxo_id) AS utxo_count FROM trading_platform.kyc_audit kyc JOIN trading_platform.utxos u ON kyc.user_id = u.user_id WHERE kyc.status IN ('pending', 'rejected') GROUP BY kyc.user_id, kyc.status HAVING COUNT(u.utxo_id) > 5;

[User] Present the final list ordered by the UTXO count in descending order.

[Assistant] SELECT kyc.user_id, kyc.status, COUNT(u.utxo_id) AS utxo_count FROM trading_platform.kyc_audit kyc JOIN trading_platform.utxos u ON kyc.user_id = u.user_id WHERE kyc.status IN ('pending', 'rejected') GROUP BY kyc.user_id, kyc.status HAVING COUNT(u.utxo_id) > 5 ORDER BY utxo_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 trading_platform.utxos ( utxo_id.text, transaction_id.text, output_index.integer, address.text, amount.numeric, spent.boolean )
CREATE TABLE trading_platform.kyc_audit ( kyc_audit_id.text, user_id.text, status.text, reviewed_at.timestamp )


[User] Find pairs of wallet IDs that belong to the same user, showing the user ID and the two wallet IDs.

[Assistant] SELECT w1.user_id, w1.wallet_id AS wallet1_id, w2.wallet_id AS wallet2_id FROM web3.wallets w1 JOIN web3.wallets w2 ON w1.user_id = w2.user_id AND w1.wallet_id < w2.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 text, user_id text, address text, private_key text, created_at timestamp )


[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] List all medical record entries where the treatment_plan mentions a medication name. Return patient_id, record_id, and the matching medication_name.

[Assistant]
SELECT mr.patient_id,
       mr.record_id,
       m.medication_name
FROM healthcare.medical_records AS mr
JOIN healthcare.medications AS m
  ON mr.treatment_plan ILIKE '%' || m.medication_name || '%';

[User] Actually, only include medications manufactured by 'Pfizer'.

[Assistant]
SELECT mr.patient_id,
       mr.record_id,
       m.medication_name
FROM healthcare.medical_records AS mr
JOIN healthcare.medications AS m
  ON mr.treatment_plan ILIKE '%' || m.medication_name || '%'
WHERE m.manufacturer = 'Pfizer';

[User] Also sort the results by record_date descending.

[Assistant]
SELECT mr.patient_id,
       mr.record_id,
       m.medication_name
FROM healthcare.medical_records AS mr
JOIN healthcare.medications AS m
  ON mr.treatment_plan ILIKE '%' || m.medication_name || '%'
WHERE m.manufacturer = 'Pfizer'
ORDER BY mr.record_date DESC;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE healthcare.patients (
    patient_id character varying(64) NOT NULL,  -- unique identifier for the patient
    first_name character varying(100) NOT NULL, -- patient's first name
    last_name character varying(100) NOT NULL, -- patient's last name
    date_of_birth date NOT NULL, -- patient's date of birth
    gender character varying(10), -- patient's gender (e.g., Male, Female, Other)
    address text, -- patient's home address
    phone_number character varying(20), -- patient's phone number
    email character varying(128) UNIQUE, -- patient's email address
    emergency_contact_name character varying(200), -- name of emergency contact
    emergency_contact_phone character varying(20), -- phone number of emergency contact
    created_at timestamp with time zone NOT NULL DEFAULT current_timestamp, -- record creation time
    updated_at timestamp with time zone NOT NULL DEFAULT current_timestamp, -- record last update time
    PRIMARY KEY (patient_id)
)
CREATE TABLE healthcare.doctors (
    doctor_id character varying(64) NOT NULL,  -- unique identifier for the doctor
    first_name character varying(100) NOT NULL, -- doctor's first name
    last_name character varying(100) NOT NULL, -- doctor's last name
    specialty character varying(100) NOT NULL, -- doctor's medical specialty
    license_number character varying(50) UNIQUE NOT NULL, -- doctor's medical license number
    phone_number character varying(20), -- doctor's contact phone
    email character varying(128) UNIQUE, -- doctor's contact email
    hospital_affiliation_id character varying(64), -- FK to hospitals table (optional)
    created_at timestamp with time zone NOT NULL DEFAULT current_timestamp,
    updated_at timestamp with time zone NOT NULL DEFAULT current_timestamp,
    PRIMARY KEY (doctor_id)
)
CREATE TABLE healthcare.appointments (
    appointment_id character varying(64) NOT NULL, -- unique identifier for the appointment
    patient_id character varying(64) NOT NULL, -- FK to patients table
    doctor_id character varying(64) NOT NULL, -- FK to doctors table
    appointment_time timestamp with time zone NOT NULL, -- date and time of the appointment
    duration_minutes integer NOT NULL, -- expected duration in minutes
    reason text, -- reason for the visit
    status character varying(32) NOT NULL, -- e.g., Scheduled, Completed, Cancelled, No-show
    location_id character varying(64), -- FK to a potential locations/clinics table
    notes text, -- notes related to scheduling
    created_at timestamp with time zone NOT NULL DEFAULT current_timestamp,
    PRIMARY KEY (appointment_id)
)
CREATE TABLE healthcare.medical_records (
    record_id character varying(64) NOT NULL,  -- unique identifier for the medical record entry
    patient_id character varying(64) NOT NULL, -- FK to patients table
    appointment_id character varying(64) UNIQUE, -- FK to appointments table (can be null if record not tied to specific appt)
    doctor_id character varying(64) NOT NULL, -- FK to doctors table (doctor creating the record)
    record_date timestamp with time zone NOT NULL, -- date the record/observation was made
    chief_complaint text, -- patient's primary reason for visit
    present_illness_history text, -- detailed history of the current issue
    past_medical_history text, -- relevant past conditions/surgeries
    physical_examination_notes text, -- findings from the physical exam
    assessment text, -- doctor's assessment/diagnosis summary
    treatment_plan text, -- planned course of action
    vitals jsonb, -- store vitals like BP, HR, Temp as structured JSON
    created_at timestamp with time zone NOT NULL DEFAULT current_timestamp,
    PRIMARY KEY (record_id)
)
CREATE TABLE healthcare.medications (
    medication_id character varying(64) NOT NULL, -- unique identifier for the medication type
    medication_name character varying(255) NOT NULL, -- common or brand name
    generic_name character varying(255), -- generic chemical name
    manufacturer character varying(100), -- drug manufacturer
    ndc_code character varying(20) UNIQUE, -- National Drug Code (optional but useful)
    description text, -- description of the medication
    PRIMARY KEY (medication_id)
)
CREATE TABLE healthcare.insurance_plans (
    plan_id character varying(64) NOT NULL, -- unique identifier for the insurance plan
    plan_name character varying(200) NOT NULL, -- name of the insurance plan
    insurance_provider character varying(100) NOT NULL, -- name of the insurance company
    plan_type character varying(50), -- e.g., PPO, HMO, EPO
    contact_phone character varying(20), -- provider contact number
    website character varying(255), -- provider website
    PRIMARY KEY (plan_id)
)
CREATE TABLE healthcare.patient_insurance (
    patient_insurance_id character varying(64) NOT NULL, -- unique identifier for this patient-plan link
    patient_id character varying(64) NOT NULL, -- FK to patients table
    plan_id character varying(64) NOT NULL, -- FK to insurance_plans table
    policy_number character varying(100) NOT NULL, -- patient's policy number
    group_number character varying(100), -- group number, if applicable
    subscriber_name character varying(200), -- name of the primary policy holder
    effective_date date NOT NULL, -- date the coverage begins
    expiration_date date, -- date the coverage ends (if known)
    is_primary boolean NOT NULL DEFAULT true, -- indicates if this is the primary insurance
    PRIMARY KEY (patient_insurance_id),
    UNIQUE (patient_id, plan_id, policy_number) -- ensure a patient doesn't have the same policy twice
)


[User] List the content and sent time for messages sent by user 'U101'.

[Assistant] SELECT content, sent_at FROM social_media.messages WHERE sender_user_id = 'U101';

[User] Could you also include the group name for those messages and only show messages sent in group chats?

[Assistant] SELECT m.content, m.sent_at, c.name AS group_name FROM social_media.messages m JOIN social_media.conversations c ON m.conversation_id = c.conversation_id WHERE m.sender_user_id = 'U101' AND c.type = 'group';

[User] Now filter to include only messages sent in June 2024 and order them by sent time descending.

[Assistant] SELECT m.content, m.sent_at, c.name AS group_name FROM social_media.messages m JOIN social_media.conversations c ON m.conversation_id = c.conversation_id WHERE m.sender_user_id = 'U101' AND c.type = 'group' AND m.sent_at >= '2024-06-01' AND m.sent_at < '2024-07-01' ORDER BY m.sent_at DESC;

[User] Also limit the results to the top 15.

[Assistant] SELECT m.content, m.sent_at, c.name AS group_name FROM social_media.messages m JOIN social_media.conversations c ON m.conversation_id = c.conversation_id WHERE m.sender_user_id = 'U101' AND c.type = 'group' AND m.sent_at >= '2024-06-01' AND m.sent_at < '2024-07-01' ORDER BY m.sent_at DESC LIMIT 15;

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, -- unique identifier for the message
    conversation_id character varying(64) NOT NULL, -- identifier for the conversation thread (FK to conversations.conversation_id)
    sender_user_id character varying(64) NOT NULL, -- identifier of the sender (FK to users.user_id)
    content text, -- textual content of the message
    media_url text, -- URL to attached media (image/video)
    media_type character varying(20), -- type of media ('image', 'video', null)
    sent_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, -- timestamp when message was sent
    read_at timestamp, -- timestamp when message was read by recipient(s)
    PRIMARY KEY (message_id)
)


[User] List all users whose email contains the word 'block', along with their username and registration timestamp.

[Assistant]
SELECT user_id, username, email, created_at
FROM web3.users
WHERE email ILIKE '%block%';

[User] Can you also include the total number of such users in the result?

[Assistant]
SELECT user_id, username, email, created_at, COUNT(*) OVER() AS total_matching_users
FROM web3.users
WHERE email ILIKE '%block%';

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE web3.users ( user_id text, username text, email text, password_hash text, created_at timestamp )


[User] Show me all reservations with more than 2 adults, along with their property names and room types.

[Assistant] SELECT r.reservation_id, p.property_name, rt.room_type_name, r.check_in_date, r.check_out_date, r.num_adults FROM hospitality_technology.reservations r JOIN hospitality_technology.properties p ON r.property_id = p.property_id JOIN hospitality_technology.room_types rt ON r.room_type_id = rt.room_type_id WHERE r.num_adults > 2;

[User] Now, include only reservations with a total amount over $500 and order them by check-in date.

[Assistant] SELECT r.reservation_id, p.property_name, rt.room_type_name, r.check_in_date, r.check_out_date, r.num_adults, r.total_amount FROM hospitality_technology.reservations r JOIN hospitality_technology.properties p ON r.property_id = p.property_id JOIN hospitality_technology.room_types rt ON r.room_type_id = rt.room_type_id WHERE r.num_adults > 2 AND r.total_amount > 500 ORDER BY r.check_in_date;

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

[Assistant] SELECT r.reservation_id, r.guest_id, p.property_name, rt.room_type_name, r.check_in_date, r.check_out_date, r.num_adults, r.total_amount FROM hospitality_technology.reservations r JOIN hospitality_technology.properties p ON r.property_id = p.property_id JOIN hospitality_technology.room_types rt ON r.room_type_id = rt.room_type_id WHERE r.num_adults > 2 AND r.total_amount > 500 ORDER BY r.check_in_date;

[User] Actually, I need to see only reservations from properties with a star rating of 4.0 or higher.

[Assistant] SELECT r.reservation_id, r.guest_id, p.property_name, rt.room_type_name, r.check_in_date, r.check_out_date, r.num_adults, r.total_amount, p.star_rating FROM hospitality_technology.reservations r JOIN hospitality_technology.properties p ON r.property_id = p.property_id JOIN hospitality_technology.room_types rt ON r.room_type_id = rt.room_type_id WHERE r.num_adults > 2 AND r.total_amount > 500 AND p.star_rating >= 4.0 ORDER BY r.check_in_date;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE hospitality_technology.properties ( property_id character varying(64) NOT NULL, property_name character varying(255) NOT NULL, address_line1 character varying(255) NOT NULL, address_line2 character varying(255), city character varying(100) NOT NULL, state_province character varying(100), postal_code character varying(20) NOT NULL, country_code character varying(3) NOT NULL, phone_number character varying(30), email_address character varying(255), property_type character varying(50) NOT NULL, star_rating numeric(2,1), timezone character varying(64) NOT NULL, manager_staff_id character varying(64), created_at timestamp with time zone NOT NULL DEFAULT current_timestamp, updated_at timestamp with time zone NOT NULL DEFAULT current_timestamp, PRIMARY KEY (property_id) )
CREATE TABLE hospitality_technology.rooms ( room_id text PRIMARY KEY, property_id text, room_number text, room_type_id text, floor int, status text, is_smoking boolean, features text, current_condition text, last_cleaned_at timestamp )
CREATE TABLE hospitality_technology.guests ( guest_id text, first_name text, last_name text, email text, phone_number text, date_of_birth date, address_line1 text, city text, state_province text, postal_code text, country_code text, preferences text, loyalty_member_id text, communication_consent boolean, created_at timestamp, updated_at timestamp )
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 text, property_id text, first_name text, last_name text, position text, work_email text, work_phone text, hire_date date, termination_date date, is_active boolean, access_level integer, manager_id text, created_at timestamp )
CREATE TABLE hospitality_technology.services ( service_id text PRIMARY KEY, property_id text, service_name text, description text, category text, price numeric, unit text, is_available boolean, department text )
CREATE TABLE hospitality_technology.service_orders ( order_id character varying(64) NOT NULL, reservation_id character varying(64), guest_id character varying(64) NOT NULL, service_id character varying(64) NOT NULL, staff_id_ordered character varying(64), staff_id_delivered character varying(64), order_timestamp timestamp with time zone NOT NULL DEFAULT current_timestamp, delivery_timestamp timestamp with time zone, quantity integer NOT NULL DEFAULT 1, unit_price numeric(10, 2) NOT NULL, total_price numeric(12, 2) NOT NULL, status character varying(50) NOT NULL, notes text, bill_id character varying(64), PRIMARY KEY (order_id), FOREIGN KEY (reservation_id) REFERENCES hospitality_technology.reservations(reservation_id), FOREIGN KEY (guest_id) REFERENCES hospitality_technology.guests(guest_id), FOREIGN KEY (service_id) REFERENCES hospitality_technology.services(service_id), FOREIGN KEY (staff_id_ordered) REFERENCES hospitality_technology.staff(staff_id), FOREIGN KEY (staff_id_delivered) REFERENCES hospitality_technology.staff(staff_id) )
CREATE TABLE hospitality_technology.payments ( payment_id.text, reservation_id.text, guest_id.text, bill_id.text, amount.numeric, currency_code.text, payment_method.text, card_type.text, card_last_four.text, transaction_ref.text, payment_timestamp.timestamp, status.text, staff_id_processed.text, notes.text )
CREATE TABLE hospitality_technology.reviews ( review_id character varying(64) NOT NULL, property_id character varying(64) NOT NULL, reservation_id character varying(64) UNIQUE, guest_id character varying(64) NOT NULL, rating_overall integer, rating_cleanliness integer, rating_service integer, rating_location integer, rating_value integer, comment text, review_source character varying(100), review_date timestamp with time zone NOT NULL DEFAULT current_timestamp, is_public boolean DEFAULT true, staff_response text, response_staff_id character varying(64), response_date timestamp with time zone, PRIMARY KEY (review_id), FOREIGN KEY (property_id) REFERENCES hospitality_technology.properties(property_id), FOREIGN KEY (reservation_id) REFERENCES hospitality_technology.reservations(reservation_id), FOREIGN KEY (guest_id) REFERENCES hospitality_technology.guests(guest_id), FOREIGN KEY (response_staff_id) REFERENCES hospitality_technology.staff(staff_id) )


[User] Get the total fuel cost per route, showing route_number and the sum of total_cost for all fuel logs associated with trips on that route.

[Assistant]
SELECT r.route_number,
       SUM(fl.total_cost) AS total_fuel_cost
FROM transportation.routes r
JOIN transportation.trips t ON r.route_id = t.route_id
JOIN transportation.fuel_logs fl ON t.trip_id = fl.trip_id
GROUP BY r.route_number;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE transportation.vehicles ( vehicle_id.text, license_plate.text, vin.text, make.text, model.text, year.integer, type.text, capacity.integer, fuel_type.text, status.text, depot_id.text, acquisition_date.date )
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 )
CREATE TABLE transportation.trips ( trip_id.text, route_id.text, vehicle_id.text, driver_id.text, scheduled_departure.timestamp, actual_departure.timestamp, scheduled_arrival.timestamp, actual_arrival.timestamp, origin_location_id.text, destination_location_id.text, status.text, passenger_count.integer, cargo_manifest_id.text )
CREATE TABLE transportation.fuel_logs ( fuel_log_id.text, vehicle_id.text, trip_id.text, log_timestamp.timestamp, fuel_type.text, quantity.numeric, unit.text, cost_per_unit.numeric, total_cost.numeric, odometer_reading.integer, location_id.text )
CREATE TABLE transportation.passengers ( passenger_id.text, first_name.text, last_name.text, email.text, phone_number.text, date_of_birth.date, loyalty_program_id.text, created_at.timestamp )


[User] What is the total sum of all amounts for all UTXOs in the system, regardless of whether they are spent or unspent?

[Assistant] SELECT SUM(amount) FROM trading_platform.utxos

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 character varying(64) NOT NULL,  -- unique identifier for the wallet
    user_id character varying(64) NOT NULL, -- identifier of the user owning the wallet
    address character varying(128) NOT NULL, -- address of the wallet
    private_key text NOT NULL, -- private key of the wallet
    created_at timestamp NOT NULL, -- time when the wallet was created
    PRIMARY KEY (wallet_id)
)
CREATE TABLE trading_platform.orders ( order_id character varying(64) NOT NULL, user_id character varying(64) NOT NULL, wallet_id character varying(64) NOT NULL, asset_id character varying(64) NOT NULL, order_type character varying(32) NOT NULL, quantity numeric(38,14) NOT NULL, price numeric(38,14) NOT NULL, status character varying(32) NOT NULL, created_at timestamp NOT NULL, PRIMARY KEY (order_id) )
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.assets (
    asset_id character varying(64) NOT NULL,  -- unique identifier for the asset
    name character varying(128) NOT NULL, -- name of the asset
    symbol character varying(32) NOT NULL, -- symbol of the asset
    type character varying(32) NOT NULL, -- type of the asset (e.g., cryptocurrency, stock)
    PRIMARY KEY (asset_id)
)
CREATE TABLE trading_platform.utxos (
    utxo_id character varying(64) NOT NULL,  -- unique identifier for the UTXO
    transaction_id character varying(64) NOT NULL, -- identifier of the transaction that created the UTXO
    output_index integer NOT NULL, -- index of the output in the transaction
    address character varying(128) NOT NULL, -- address that can spend the UTXO
    amount numeric(38,14) NOT NULL, -- amount of the asset in the UTXO
    spent boolean NOT NULL, -- whether the UTXO has been spent
    PRIMARY KEY (utxo_id)
)
CREATE TABLE trading_platform.dapps ( dapp_id.text, name.text, description.text, url.text )
CREATE TABLE trading_platform.metadata (
    metadata_id character varying(64) NOT NULL,  -- unique identifier for the metadata
    asset_id character varying(64) NOT NULL, -- identifier of the asset the metadata is associated with
    key character varying(128) NOT NULL, -- key of the metadata
    value text NOT NULL, -- value of the metadata
    PRIMARY KEY (metadata_id)
)
CREATE TABLE trading_platform.kyc_audit ( kyc_audit_id.text, user_id.text, status.text, reviewed_at.timestamp )
CREATE TABLE trading_platform.logs (
    log_id character varying(64) NOT NULL,  -- unique identifier for the log entry
    user_id character varying(64), -- identifier of the user associated with the log entry
    action character varying(128) NOT NULL, -- action performed
    details text NOT NULL, -- details of the action
    logged_at timestamp NOT NULL, -- time when the log entry was created
    PRIMARY KEY (log_id)
)
CREATE TABLE trading_platform.notifications ( notification_id.text, user_id.text, message.text, sent_at.timestamp, read_at.timestamp )


[User] List all users and the total quantity of orders they have placed for 'buy' orders.

[Assistant] SELECT t1.username, SUM(t2.quantity) FROM trading_platform.users AS t1 JOIN trading_platform.orders AS t2 ON t1.user_id = t2.user_id WHERE t2.order_type = 'buy' GROUP BY t1.username;

[User] Filter this list to only include users whose total buy quantity is greater than 100.

[Assistant] SELECT t1.username, SUM(t2.quantity) FROM trading_platform.users AS t1 JOIN trading_platform.orders AS t2 ON t1.user_id = t2.user_id WHERE t2.order_type = 'buy' GROUP BY t1.username HAVING SUM(t2.quantity) > 100;

[User] For those users, what is the average price of their 'buy' orders? Show username and average price.

[Assistant] SELECT t1.username, AVG(t2.price) FROM trading_platform.users AS t1 JOIN trading_platform.orders AS t2 ON t1.user_id = t2.user_id WHERE t2.order_type = 'buy' GROUP BY t1.username HAVING SUM(t2.quantity) > 100;

System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE trading_platform.users ( user_id.text, username.text, email.text, password_hash.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.assets ( asset_id.text, name.text, symbol.text, type.text )
CREATE TABLE trading_platform.dapps ( dapp_id.text, name.text, description.text, url.text )
CREATE TABLE trading_platform.kyc_audit ( kyc_audit_id.text, user_id.text, status.text, reviewed_at.timestamp )
CREATE TABLE trading_platform.notifications ( notification_id.text, user_id.text, message.text, sent_at.timestamp, read_at.timestamp )


[User] List all post IDs and their corresponding hashtag names for posts that include media.

[Assistant]
SELECT ph.post_id, h.tag_name
FROM social_media.post_hashtags ph
JOIN social_media.hashtags h ON ph.hashtag_id = h.hashtag_id
JOIN social_media.posts p ON ph.post_id = p.post_id
WHERE p.media_url IS NOT NULL AND p.media_url != '';

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.posts ( post_id text PRIMARY KEY, user_id text, content text, media_url text, media_type text, created_at timestamp, updated_at timestamp, visibility text, location_lat numeric, location_lon numeric )
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 character varying(64) NOT NULL, -- unique identifier for the post-hashtag link
    post_id character varying(64) NOT NULL, -- identifier of the post (FK to posts.post_id)
    hashtag_id character varying(64) NOT NULL, -- identifier of the hashtag (FK to hashtags.hashtag_id)
    PRIMARY KEY (post_hashtag_id),
    CONSTRAINT unique_post_hashtag UNIQUE (post_id, hashtag_id) -- prevent duplicate tags on a post
)
CREATE TABLE social_media.messages (
    message_id character varying(64) NOT NULL, -- unique identifier for the message
    conversation_id character varying(64) NOT NULL, -- identifier for the conversation thread (FK to conversations.conversation_id)
    sender_user_id character varying(64) NOT NULL, -- identifier of the sender (FK to users.user_id)
    content text, -- textual content of the message
    media_url text, -- URL to attached media (image/video)
    media_type character varying(20), -- type of media ('image', 'video', null)
    sent_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, -- timestamp when message was sent
    read_at timestamp, -- timestamp when message was read by recipient(s)
    PRIMARY KEY (message_id)
)
CREATE TABLE social_media.conversations ( conversation_id text PRIMARY KEY, created_at timestamp, last_message_at timestamp, is_group_chat bool, group_name text )
CREATE TABLE social_media.conversation_participants (
    participant_id character varying(64) NOT NULL, -- unique identifier for the participant entry
    conversation_id character varying(64) NOT NULL, -- identifier of the conversation (FK to conversations.conversation_id)
    user_id character varying(64) NOT NULL, -- identifier of the user in the conversation (FK to users.user_id)
    joined_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, -- timestamp when user joined the conversation
    last_read_at timestamp, -- timestamp indicating up to when the user has read messages
    PRIMARY KEY (participant_id),
    CONSTRAINT unique_user_conversation UNIQUE (conversation_id, user_id) -- prevent user being added multiple times
)
CREATE TABLE social_media.notifications (
    notification_id character varying(64) NOT NULL, -- unique identifier for the notification
    recipient_user_id character varying(64) NOT NULL, -- user receiving the notification (FK to users.user_id)
    sender_user_id character varying(64), -- user triggering the notification (FK to users.user_id, can be null for system notifications)
    notification_type character varying(30) NOT NULL, -- type of notification ('like', 'comment', 'follow', 'mention', 'message')
    target_entity_id character varying(64), -- ID of the related entity (post_id, comment_id, user_id, conversation_id)
    target_entity_type character varying(20), -- type of the related entity ('post', 'comment', 'user', 'conversation')
    created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, -- timestamp notification was created
    read_at timestamp, -- timestamp notification was marked as read
    PRIMARY KEY (notification_id)
)
CREATE TABLE social_media.user_settings ( setting_id character varying(64) NOT NULL, user_id character varying(64) NOT NULL UNIQUE, theme character varying(20) DEFAULT 'light', email_notifications_enabled boolean DEFAULT true, push_notifications_enabled boolean DEFAULT true, private_profile boolean DEFAULT false, updated_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, PRIMARY KEY (setting_id) )


[User] Show a list of all fuel refueling events for each trip, including the trip ID, fuel type, quantity, total cost, and the name of the refueling location.

[Assistant]
SELECT fl.trip_id, fl.fuel_type, fl.quantity, fl.total_cost, l.name AS location_name
FROM transportation.fuel_logs fl
JOIN transportation.locations l ON fl.location_id = l.location_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 transportation.vehicles ( vehicle_id text, license_plate text, vin text, make text, model text, year integer, type text, capacity integer, fuel_type text, status text, depot_id text, acquisition_date date )
CREATE TABLE transportation.drivers ( driver_id text, employee_id text, first_name text, last_name text, license_number text, license_expiry_date date, contact_number text, email text, hire_date date, status text )
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 )
CREATE TABLE transportation.trips ( trip_id text, route_id text, vehicle_id text, driver_id text, scheduled_departure timestamp, actual_departure timestamp, scheduled_arrival timestamp, actual_arrival timestamp, origin_location_id text, destination_location_id text, status text, passenger_count integer, cargo_manifest_id text )
CREATE TABLE transportation.locations ( location_id text, 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, vehicle_id text, service_date date, odometer_reading integer, service_type text, description text, cost numeric, mechanic_name text, next_service_due_date date )
CREATE TABLE transportation.fuel_logs ( fuel_log_id text, vehicle_id text, trip_id text, log_timestamp timestamp, fuel_type text, quantity numeric, unit text, cost_per_unit numeric, total_cost numeric, odometer_reading integer, location_id text )
CREATE TABLE transportation.passengers ( passenger_id text, first_name text, last_name text, email text, phone_number text, date_of_birth date, loyalty_program_id text, created_at timestamp )


[User] How many reviews does each staff member respond to, along with their full name and the average response time in hours?

[Assistant]
SELECT st.staff_id,
       st.first_name || ' ' || st.last_name AS staff_full_name,
       COUNT(*) AS response_count,
       AVG(EXTRACT(EPOCH FROM (r.response_date - r.review_date)) / 3600) AS avg_response_time_hours
FROM hospitality_technology.reviews r
JOIN hospitality_technology.staff st
  ON r.response_staff_id = st.staff_id
WHERE r.response_date IS NOT NULL
GROUP BY st.staff_id, st.first_name, st.last_name;

[User] Filter to only include staff who responded to at least 5 reviews.

[Assistant]
SELECT sub.staff_id,
       sub.staff_full_name,
       sub.response_count,
       sub.avg_response_time_hours
FROM (
  SELECT st.staff_id,
         st.first_name || ' ' || st.last_name AS staff_full_name,
         COUNT(*) AS response_count,
         AVG(EXTRACT(EPOCH FROM (r.response_date - r.review_date)) / 3600) AS avg_response_time_hours
  FROM hospitality_technology.reviews r
  JOIN hospitality_technology.staff st
    ON r.response_staff_id = st.staff_id
  WHERE r.response_date IS NOT NULL
  GROUP BY st.staff_id, st.first_name, st.last_name
) sub
WHERE sub.response_count >= 5;

[User] Also order the result by average response time ascending.

[Assistant]
SELECT sub.staff_id,
       sub.staff_full_name,
       sub.response_count,
       sub.avg_response_time_hours
FROM (
  SELECT st.staff_id,
         st.first_name || ' ' || st.last_name AS staff_full_name,
         COUNT(*) AS response_count,
         AVG(EXTRACT(EPOCH FROM (r.response_date - r.review_date)) / 3600) AS avg_response_time_hours
  FROM hospitality_technology.reviews r
  JOIN hospitality_technology.staff st
    ON r.response_staff_id = st.staff_id
  WHERE r.response_date IS NOT NULL
  GROUP BY st.staff_id, st.first_name, st.last_name
) sub
WHERE sub.response_count >= 5
ORDER BY sub.avg_response_time_hours 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.properties ( property_id text PRIMARY KEY, property_name text, address_line1 text, address_line2 text, city text, state_province text, postal_code text, country_code text, phone_number text, email_address text, property_type text, star_rating numeric, timezone text, manager_staff_id text, created_at timestamp, updated_at timestamp )
CREATE TABLE hospitality_technology.rooms (
    room_id 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.room_types ( room_type_id text, property_id text, type_name text, description text, base_rate numeric, max_occupancy integer, bed_type text, area_sqft numeric, amenities text )
CREATE TABLE hospitality_technology.guests ( guest_id text PRIMARY KEY, first_name text, last_name text, email text, phone_number text, date_of_birth date, address_line1 text, city text, state_province text, postal_code text, country_code text, preferences text, loyalty_member_id text, communication_consent boolean, created_at timestamp, updated_at timestamp )
CREATE TABLE hospitality_technology.staff ( staff_id text, property_id text, first_name text, last_name text, position text, work_email text, work_phone text, hire_date date, termination_date date, is_active boolean, access_level integer, manager_id text, created_at timestamp )
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)
)
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 character varying(64) NOT NULL, property_id character varying(64) NOT NULL, reservation_id character varying(64) UNIQUE, guest_id character varying(64) NOT NULL, rating_overall integer, rating_cleanliness integer, rating_service integer, rating_location integer, rating_value integer, comment text, review_source character varying(100), review_date timestamp with time zone NOT NULL DEFAULT current_timestamp, is_public boolean DEFAULT true, staff_response text, response_staff_id character varying(64), response_date timestamp with time zone, PRIMARY KEY (review_id), FOREIGN KEY (property_id) REFERENCES hospitality_technology.properties(property_id), FOREIGN KEY (reservation_id) REFERENCES hospitality_technology.reservations(reservation_id), FOREIGN KEY (guest_id) REFERENCES hospitality_technology.guests(guest_id), FOREIGN KEY (response_staff_id) REFERENCES hospitality_technology.staff(staff_id) )


[User] List group conversation names and the number of messages sent in each conversation after January 1, 2023.

[Assistant] SELECT c.group_name, COUNT(m.message_id) FROM social_media.conversations c JOIN social_media.messages m ON c.conversation_id = m.conversation_id WHERE c.is_group_chat = true AND m.sent_at >= '2023-01-01' GROUP BY c.conversation_id, c.group_name;

[User] Only show conversations that have more than 100 messages sent after that date.

[Assistant] SELECT c.group_name, COUNT(m.message_id) FROM social_media.conversations c JOIN social_media.messages m ON c.conversation_id = m.conversation_id WHERE c.is_group_chat = true AND m.sent_at >= '2023-01-01' GROUP BY c.conversation_id, c.group_name HAVING COUNT(m.message_id) > 100;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE 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.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.post_hashtags ( post_hashtag_id text, post_id text, hashtag_id text )
CREATE TABLE social_media.messages ( message_id text, conversation_id text, sender_user_id text, content text, media_url text, media_type text, sent_at timestamp, read_at timestamp )
CREATE TABLE social_media.conversations ( conversation_id 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] List usernames and the length of their 'bio' field for users whose 'is_verified' status is true.

[Assistant] SELECT username, LENGTH(bio) AS bio_length FROM social_media.users WHERE is_verified IS 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 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] List all premium payments for policy 'POL123'. Show payment ID, payment date, amount paid, and status.

[Assistant] SELECT payment_id, payment_date, amount_paid, status FROM insurance.premium_payments WHERE policy_id = 'POL123';

[User] Only show payments made on or after January 1, 2024.

[Assistant] SELECT payment_id, payment_date, amount_paid, status FROM insurance.premium_payments WHERE policy_id = 'POL123' AND payment_date >= '2024-01-01';

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE insurance.premium_payments (
    payment_id character varying(64) NOT NULL, -- unique identifier for the payment
    policy_id character varying(64) NOT NULL, -- identifier of the policy the payment is for (FK to policies)
    customer_id character varying(64) NOT NULL, -- identifier of the customer making the payment (FK to customers)
    payment_date timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, -- date the payment was received
    amount_paid numeric(12, 2) NOT NULL, -- amount of the payment
    payment_method character varying(50), -- e.g., Credit Card, Bank Transfer, Check
    transaction_reference character varying(128) UNIQUE, -- reference from payment processor
    due_date date, -- due date for this payment installment
    payment_period_start date, -- start date of the period this payment covers
    payment_period_end date, -- end date of the period this payment covers
    status character varying(30) NOT NULL DEFAULT 'Completed', -- e.g., Completed, Pending, Failed, Refunded
    PRIMARY KEY (payment_id)
)


[User] Provide a count of notifications, separated by whether they have been read or not.

[Assistant] SELECT CASE WHEN T1.read_at IS NULL THEN 'Unread' ELSE 'Read' END, count(T1.notification_id) FROM trading_platform.notifications AS T1 GROUP BY CASE WHEN T1.read_at IS NULL THEN 'Unread' ELSE 'Read' END

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.notifications ( notification_id.text, user_id.text, message.text, sent_at.timestamp, read_at.timestamp )


[User] Show me the number of game servers in each region and the average maximum number of players they can accommodate. Exclude any servers that are currently offline.

[Assistant] SELECT region, COUNT(server_id) AS server_count, AVG(max_players) AS average_max_players FROM gaming_technology.servers WHERE status != 'offline' GROUP BY region;

[User] Please filter the results to only include regions that have more than 5 active servers.

[Assistant] SELECT region, COUNT(server_id) AS server_count, AVG(max_players) AS average_max_players FROM gaming_technology.servers WHERE status != 'offline' GROUP BY region HAVING COUNT(server_id) > 5;

[User] Can you also include the total number of current players across all active servers in each of those regions?

[Assistant] SELECT region, COUNT(server_id) AS server_count, AVG(max_players) AS average_max_players, SUM(current_players) AS total_current_players FROM gaming_technology.servers WHERE status != 'offline' GROUP BY region HAVING COUNT(server_id) > 5;

[User] Order the final results by the total number of current players in descending order.

[Assistant] SELECT region, COUNT(server_id) AS server_count, AVG(max_players) AS average_max_players, SUM(current_players) AS total_current_players FROM gaming_technology.servers WHERE status != 'offline' GROUP BY region HAVING COUNT(server_id) > 5 ORDER BY total_current_players 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 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)
)
CREATE TABLE gaming_technology.in_game_items (
    item_id uuid NOT NULL DEFAULT gen_random_uuid(), -- unique identifier for the item definition
    game_id uuid NOT NULL, -- FK linking to the game this item belongs to
    item_name character varying(150) NOT NULL, -- name of the item
    item_type character varying(50) NOT NULL, -- type (e.g., Cosmetic, Consumable, Weapon, Armor)
    description text, -- description of the item
    rarity character varying(30), -- item rarity (e.g., Common, Rare, Epic, Legendary)
    cost_currency character varying(10), -- currency code if purchasable (e.g., USD, EUR, GOLD)
    cost_amount numeric(12, 2), -- price if purchasable
    attributes jsonb, -- flexible field for item stats or properties
    PRIMARY KEY (item_id)
    -- FOREIGN KEY (game_id) REFERENCES gaming_technology.games(game_id)
)
CREATE TABLE gaming_technology.player_inventory (
    inventory_id uuid NOT NULL DEFAULT gen_random_uuid(), -- unique identifier for an inventory entry
    player_id uuid NOT NULL, -- FK linking to the player owning the item
    item_id uuid NOT NULL, -- FK linking to the item definition
    quantity integer NOT NULL DEFAULT 1, -- number of items held (for stackable items)
    acquired_at timestamp with time zone NOT NULL DEFAULT CURRENT_TIMESTAMP, -- when the item was acquired
    instance_data jsonb, -- data specific to this instance (e.g., weapon mods, durability)
    PRIMARY KEY (inventory_id),
    -- Optional unique constraint if items are non-stackable or unique instances
    -- UNIQUE (player_id, item_id) -- Use if quantity is always 1
    -- FOREIGN KEY (player_id) REFERENCES gaming_technology.players(player_id),
    -- FOREIGN KEY (item_id) REFERENCES gaming_technology.in_game_items(item_id)
)


[User] Show the number of employees in each department.

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

[User] Exclude departments that have less than 3 employees.

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

[User] Can you also show the average hire_date for employees in each department?

[Assistant]
SELECT department, COUNT(*) AS employee_count, AVG(hire_date) AS average_hire_date
FROM financial_services.employees
group BY department
HAVING COUNT(*) >= 3;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE financial_services.accounts ( account_id text PRIMARY KEY, customer_id text, account_number text, account_type text, balance numeric, currency text, opened_date date, status text, interest_rate numeric, last_updated_at timestamp )
CREATE TABLE financial_services.transactions ( transaction_id text PRIMARY KEY, account_id text, related_account_id text, transaction_type text, amount numeric, currency text, transaction_date timestamp, effective_date date, description text, status text, reference_number text )
CREATE TABLE financial_services.trades ( trade_id text PRIMARY KEY, account_id text, security_id text, order_id text, trade_type text, quantity numeric, price_per_unit numeric, total_amount numeric, commission numeric, trade_timestamp timestamp, settlement_date date, status text, execution_venue text )
CREATE TABLE financial_services.market_data ( data_point_id bigserial PRIMARY KEY, security_id text, data_timestamp timestamp, open_price numeric, high_price numeric, low_price numeric, close_price numeric, adjusted_close_price numeric, volume bigint, source text )
CREATE TABLE financial_services.employees ( employee_id text PRIMARY KEY, first_name text, last_name text, job_title text, department text, branch_id text, email text, phone_extension text, hire_date date, termination_date date, manager_id text, status text )


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

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

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE legal_services.clients ( client_id character varying(64) NOT NULL, first_name character varying(100) NOT NULL, last_name character varying(100) NOT NULL, company_name character varying(200), email character varying(128) UNIQUE NOT NULL, phone character varying(32), address text, date_registered timestamp NOT NULL, status character varying(32) NOT NULL, PRIMARY KEY (client_id) )
CREATE TABLE legal_services.lawyers ( lawyer_id character varying(64) NOT NULL, first_name character varying(100) NOT NULL, last_name character varying(100) NOT NULL, bar_number character varying(64) UNIQUE NOT NULL, firm_id character varying(64), email character varying(128) UNIQUE NOT NULL, phone character varying(32), specialization text, hire_date timestamp NOT NULL, is_partner boolean DEFAULT false, PRIMARY KEY (lawyer_id) )
CREATE TABLE legal_services.law_firms ( firm_id character varying(64) NOT NULL, firm_name character varying(200) NOT NULL, address text NOT NULL, phone character varying(32), website character varying(255), founded_date date, managing_partner_id character varying(64), PRIMARY KEY (firm_id) )
CREATE TABLE legal_services.cases ( case_id character varying(64) NOT NULL, case_number character varying(100) UNIQUE, case_name text NOT NULL, client_id character varying(64) NOT NULL, lead_lawyer_id character varying(64) NOT NULL, case_type character varying(100) NOT NULL, status character varying(50) NOT NULL, date_opened timestamp NOT NULL, date_closed timestamp, description text, court_jurisdiction character varying(128), PRIMARY KEY (case_id) )
CREATE TABLE legal_services.documents ( document_id character varying(64) NOT NULL, case_id character varying(64) NOT NULL, document_name character varying(255) NOT NULL, document_type character varying(100), storage_path text NOT NULL, uploaded_by_lawyer_id character varying(64), upload_timestamp timestamp NOT NULL, version integer DEFAULT 1, description text, PRIMARY KEY (document_id) )
CREATE TABLE legal_services.time_entries ( entry_id character varying(64) NOT NULL, case_id character varying(64) NOT NULL, lawyer_id character varying(64) NOT NULL, date_worked date NOT NULL, hours_spent numeric(5, 2) NOT NULL CHECK (hours_spent > 0), billing_rate numeric(10, 2) NOT NULL, description text NOT NULL, is_billable boolean DEFAULT true, is_billed boolean DEFAULT false, invoice_id character varying(64), created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, PRIMARY KEY (entry_id) )
CREATE TABLE legal_services.appointments ( appointment_id character varying(64) NOT NULL, client_id character varying(64) NOT NULL, lawyer_id character varying(64) NOT NULL, case_id character varying(64), start_time timestamp NOT NULL, end_time timestamp NOT NULL, location text, subject character varying(255), notes text, status character varying(50) NOT NULL, created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, PRIMARY KEY (appointment_id) )


[User] Show all tokens on the 'Arbitrum' chain from DEX pools that have a 24-hour trading volume between $100,000 and $500,000. Display token symbol, price, and volume_24h.

[Assistant]
SELECT
  token_symbol,
  price,
  volume_24h
FROM token_dexpool_info
WHERE
  chain = 'Arbitrum' AND volume_24h BETWEEN 100000 AND 500000;

[User] Include their liquidity and 6-hour price change percentage in the results.

[Assistant]
SELECT
  token_symbol,
  price,
  volume_24h,
  liquidity,
  price_change_percentage_6h
FROM token_dexpool_info
WHERE
  chain = 'Arbitrum' AND volume_24h BETWEEN 100000 AND 500000;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE project_fundraising_record ( id character varying(32) NOT NULL, project_id character varying(32) NOT NULL, project_name character varying(128) NOT NULL, rounds_name character varying(32), investment_value numeric(38,14), investment_date character varying(128), introduction character varying(128), valuation numeric(38,14) )
CREATE TABLE token_basic_info ( coin_id text, token_name text, token_symbol text, token_address text, chain text, price numeric, price_change_percentage_1h numeric, price_change_percentage_24h numeric, price_change_percentage_7d numeric, highest_price_24h numeric, lowest_price_24h numeric, market_cap numeric, market_cap_rank numeric, market_cap_change_percentage_24h text, total_volume text, narrative text, trend_rank numeric )
 "CREATE TABLE narrative_info (",
    "narrative 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, -- the id of dexpool token_name character varying(100) NOT NULL, -- the name of the token in the dexpool token_symbol character varying(100) NOT NULL, -- the token's symbol chain text, -- the chain that the dexpool resides price double precision, -- the current price of the token price_change_percentage_1h double precision, -- change in value divided by the absolute price value of the original token price in 1 hour price_change_percentage_6h double precision, -- change in value divided by the absolute price value of the original token price in 6 hours price_change_percentage_24h double precision, -- change in value divided by the absolute price value of the original token price in 24 hours makers_24h double precision, -- the makers of the dex pool in 24 hours volume_24h double precision, -- the trade volume of the dex pool in 24 hours liquidity double precision, -- the liquidity of the dex pool market_cap double precision, -- the market cap of the token trend_rank bigint, -- the rank of token in the dex pool of recent trending, value 1 expresses the most popular token. ,PRIMARY KEY (pair_address, chain) )
  "CREATE TABLE 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));"

CREATE TABLE smart_money_profit ( address character varying(100) NOT NULL, -- the user's address rank INT, -- the rank of the address in trade performance, value 1 expresses the best address. profit numeric(38,6), -- the profit user made in a month roi numeric(38,2), -- the roi of the user in a month realized_ratio numeric(38,2), -- the percentage of the user's realized profit most_profit_token character varying(100), -- the token symbol of the user's most profitable trade last_trade_time character varying(100), -- the last trade time of the user chain character varying(100), -- the chain that the address resides PRIMARY KEY (address, chain) )
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] Show the name of each agency and whether it operates at least one service location marked as accessible.

[Assistant] SELECT T1.agency_name FROM government_services.agencies AS T1 JOIN government_services.service_locations AS T2 ON T1.agency_id = T2.agency_id WHERE T2.is_accessible = TRUE GROUP BY T1.agency_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 government_services.agencies (
    agency_id character varying(64) NOT NULL, -- unique identifier for the agency
    agency_name character varying(255) NOT NULL, -- full name of the government agency
    jurisdiction_level character varying(50) NOT NULL, -- e.g., Federal, State, County, City
    primary_contact_email character varying(128),
    main_phone_number character varying(32),
    website_url character varying(255),
    established_date date,
    parent_agency_id character varying(64), -- FK to self for hierarchical structure
    PRIMARY KEY (agency_id)
)
CREATE TABLE government_services.services (
    service_id character varying(64) NOT NULL, -- unique identifier for the service
    agency_id character varying(64) NOT NULL, -- FK to agencies table
    service_name character varying(255) NOT NULL, -- name of the service (e.g., Driver's License Renewal)
    description text,
    category character varying(100), -- e.g., Licensing, Benefits, Taxation, Permits
    eligibility_criteria text, -- description of who is eligible
    standard_fee numeric(10, 2) DEFAULT 0.00, -- typical fee for the service
    average_processing_time_days integer, -- estimated processing time
    is_active boolean DEFAULT true, -- whether the service is currently offered
    online_application_url character varying(255),
    PRIMARY KEY (service_id)
)
CREATE TABLE government_services.service_locations (
    location_id character varying(64) NOT NULL, -- unique identifier for the physical location
    agency_id character varying(64) NOT NULL, -- FK to agencies table
    location_name character varying(200), -- e.g., Downtown DMV Office
    address text NOT NULL,
    city character varying(100),
    state character varying(50),
    postal_code character varying(20),
    latitude numeric(9, 6),
    longitude numeric(9, 6),
    operating_hours text, -- description of opening times
    contact_phone character varying(32),
    is_accessible boolean, -- accessibility information (e.g., wheelchair access)
    PRIMARY KEY (location_id)
)


[User] Find pairs of BUY and SELL trades from the trades table for the same account that occurred on the same settlement_date and had matching quantities.

[Assistant]
SELECT
  a.trade_id AS buy_trade_id,
  b.trade_id AS sell_trade_id,
  a.account_id,
  a.settlement_date,
  a.quantity
FROM financial_services.trades a
JOIN financial_services.trades b
  ON a.account_id = b.account_id
  AND a.settlement_date = b.settlement_date
  AND a.quantity = b.quantity
WHERE a.trade_type = 'BUY'
  AND b.trade_type = 'SELL';

[User] Only include pairs where the execution_venue is different between the two trades.

[Assistant]
SELECT
  a.trade_id AS buy_trade_id,
  b.trade_id AS sell_trade_id,
  a.account_id,
  a.settlement_date,
  a.quantity
FROM financial_services.trades a
JOIN financial_services.trades b
  ON a.account_id = b.account_id
  AND a.settlement_date = b.settlement_date
  AND a.quantity = b.quantity
WHERE a.trade_type = 'BUY'
  AND b.trade_type = 'SELL'
  AND a.execution_venue <> b.execution_venue;

[User] Sort the results by account_id ascending and settlement_date descending.

[Assistant]
SELECT
  a.trade_id AS buy_trade_id,
  b.trade_id AS sell_trade_id,
  a.account_id,
  a.settlement_date,
  a.quantity
FROM financial_services.trades a
JOIN financial_services.trades b
  ON a.account_id = b.account_id
  AND a.settlement_date = b.settlement_date
  AND a.quantity = b.quantity
WHERE a.trade_type = 'BUY'
  AND b.trade_type = 'SELL'
  AND a.execution_venue <> b.execution_venue
ORDER BY a.account_id ASC, a.settlement_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 financial_services.trades ( trade_id character varying(64) NOT NULL, account_id character varying(64) NOT NULL, security_id character varying(64) NOT NULL, order_id character varying(64), trade_type character varying(10) NOT NULL, quantity numeric(19, 8) NOT NULL, price_per_unit numeric(19, 8) NOT NULL, total_amount numeric(19, 4) NOT NULL, commission numeric(10, 4), trade_timestamp timestamp NOT NULL, settlement_date date, status character varying(32) NOT NULL, execution_venue character varying(100), PRIMARY KEY (trade_id), FOREIGN KEY (account_id) REFERENCES financial_services.accounts(account_id), FOREIGN KEY (security_id) REFERENCES financial_services.securities(security_id) )
CREATE TABLE financial_services.employees ( employee_id character varying(64) NOT NULL, first_name character varying(100) NOT NULL, last_name character varying(100) NOT NULL, job_title character varying(100) NOT NULL, department character varying(100), branch_id character varying(64), email character varying(128) NOT NULL UNIQUE, phone_extension character varying(20), hire_date date NOT NULL, termination_date date, manager_id character varying(64), status character varying(32) NOT NULL, PRIMARY KEY (employee_id), FOREIGN KEY (branch_id) REFERENCES financial_services.branches(branch_id), FOREIGN KEY (manager_id) REFERENCES financial_services.employees(employee_id) )


[User] Show the first name, last name, relationship, and percentage share for all policy beneficiaries added after January 1st, 2024.

[Assistant] SELECT first_name, last_name, relationship, percentage_share FROM insurance.policy_beneficiaries WHERE added_at >= '2024-01-01';

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE insurance.policies ( policy_id character varying(64) NOT NULL, customer_id character varying(64) NOT NULL, product_id character varying(64) NOT NULL, agent_id character varying(64), policy_number character varying(100) NOT NULL UNIQUE, start_date date NOT NULL, end_date date NOT NULL, premium_amount numeric(12, 2) NOT NULL, coverage_limit numeric(15, 2) NOT NULL, deductible numeric(10, 2) NOT NULL, status character varying(30) NOT NULL, issued_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, cancellation_date date, cancellation_reason text, PRIMARY KEY (policy_id) )
CREATE TABLE insurance.agents ( agent_id.text, first_name.text, last_name.text, agency_name.text, license_number.text, license_state.text, contact_email.text, contact_phone.text, hire_date.date, termination_date.date, status.text, commission_rate.numeric, manager_id.text )
CREATE TABLE insurance.claim_documents ( document_id.text, claim_id.text, document_type.text, file_name.text, file_path.text, file_size_bytes.integer, mime_type.text, uploaded_by.text, uploaded_at.timestamp, description.text )
CREATE TABLE insurance.policy_beneficiaries (
    beneficiary_id character varying(64) NOT NULL, -- unique identifier for the beneficiary entry
    policy_id character varying(64) NOT NULL, -- identifier of the life/relevant policy (FK to policies)
    customer_id character varying(64) NOT NULL, -- identifier of the beneficiary (could be FK to customers or store info directly)
    first_name character varying(100) NOT NULL, -- beneficiary first name (if not linking to customers table)
    last_name character varying(100) NOT NULL, -- beneficiary last name
    relationship character varying(50) NOT NULL, -- relationship to the policyholder (e.g., Spouse, Child, Parent)
    percentage_share numeric(5, 2) NOT NULL CHECK (percentage_share > 0 AND percentage_share <= 100), -- percentage of payout
    contact_info text, -- contact details for the beneficiary
    added_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
    PRIMARY KEY (beneficiary_id),
    UNIQUE (policy_id, customer_id) -- Ensure a person is listed only once per policy
)


[User] Show the total fuel cost for each month in 2023 based on the log timestamp.

[Assistant]
SELECT
    EXTRACT(MONTH FROM log_timestamp) AS log_month,
    SUM(total_cost) AS monthly_total_cost
FROM transportation.fuel_logs
WHERE EXTRACT(YEAR FROM log_timestamp) = 2023
GROUP BY 1
ORDER BY 1;

[User] Only include months where the total cost is greater than 5000 and order the results by month.

[Assistant]
SELECT
    EXTRACT(MONTH FROM log_timestamp) AS log_month,
    SUM(total_cost) AS monthly_total_cost
FROM transportation.fuel_logs
WHERE EXTRACT(YEAR FROM log_timestamp) = 2023
GROUP BY 1
HAVING SUM(total_cost) > 5000
ORDER BY 1;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE transportation.fuel_logs ( fuel_log_id character varying(64) NOT NULL, vehicle_id character varying(64) NOT NULL, trip_id character varying(64), log_timestamp timestamp with time zone NOT NULL, fuel_type character varying(32) NOT NULL, quantity numeric(10, 3) NOT NULL, unit character varying(16) NOT NULL, cost_per_unit numeric(8, 4), total_cost numeric(10, 2) NOT NULL, odometer_reading integer, location_id character varying(64), PRIMARY KEY (fuel_log_id) )