System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE gaming_technology.players (
    player_id uuid NOT NULL DEFAULT gen_random_uuid(), -- 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 usernames of players who own items of 'Legendary' rarity.

[Assistant] SELECT DISTINCT T1.username FROM players AS T1 JOIN player_inventory AS T2 ON T1.player_id = T2.player_id JOIN in_game_items AS T3 ON T2.item_id = T3.item_id WHERE T3.rarity = 'Legendary';

[User] Modify the query to also include the item name and the quantity the player owns for each such item.

[Assistant] SELECT T1.username, T3.item_name, T2.quantity FROM players AS T1 JOIN player_inventory AS T2 ON T1.player_id = T2.player_id JOIN in_game_items AS T3 ON T2.item_id = T3.item_id WHERE T3.rarity = 'Legendary';

[User] Change the request to find the total number of 'Legendary' items across all player inventories.

[Assistant] SELECT SUM(T1.quantity) FROM player_inventory AS T1 JOIN in_game_items AS T2 ON T1.item_id = T2.item_id WHERE T2.rarity = 'Legendary';

[User] Show the total number of 'Legendary' items per game, including the game title.

[Assistant] SELECT T3.title, SUM(T1.quantity) FROM player_inventory AS T1 JOIN in_game_items AS T2 ON T1.item_id = T2.item_id JOIN games AS T3 ON T2.game_id = T3.game_id WHERE T2.rarity = 'Legendary' GROUP BY T3.title;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE insurance.premium_payments ( payment_id text PRIMARY KEY, policy_id text, customer_id text, payment_date timestamp, amount_paid numeric, payment_method text, transaction_reference text, due_date date, payment_period_start date, payment_period_end date, status text )

[User] For each customer, calculate the average number of days between their consecutive premium payments.

[Assistant]
SELECT t.customer_id,
       AVG(t.days_diff) AS avg_days_between
FROM (
  SELECT p1.customer_id,
         EXTRACT(DAY FROM p2.payment_date - p1.payment_date) AS days_diff
  FROM insurance.premium_payments p1
  JOIN insurance.premium_payments p2
    ON p1.customer_id = p2.customer_id
   AND p2.payment_date > p1.payment_date
) AS t
GROUP BY t.customer_id;

[User] Exclude any payments that are not 'Completed'.

[Assistant]
SELECT t.customer_id,
       AVG(t.days_diff) AS avg_days_between
FROM (
  SELECT p1.customer_id,
         EXTRACT(DAY FROM p2.payment_date - p1.payment_date) AS days_diff
  FROM insurance.premium_payments p1
  JOIN insurance.premium_payments p2
    ON p1.customer_id = p2.customer_id
   AND p2.payment_date > p1.payment_date
  WHERE p1.status = 'Completed'
    AND p2.status = 'Completed'
) AS t
GROUP BY t.customer_id;

[User] Only include customers whose average days between payments is greater than 30 and show that value.

[Assistant]
SELECT customer_id,
       AVG(days_diff) AS avg_days_between
FROM (
  SELECT p1.customer_id,
         EXTRACT(DAY FROM p2.payment_date - p1.payment_date) AS days_diff
  FROM insurance.premium_payments p1
  JOIN insurance.premium_payments p2
    ON p1.customer_id = p2.customer_id
   AND p2.payment_date > p1.payment_date
  WHERE p1.status = 'Completed'
    AND p2.status = 'Completed'
) AS t
GROUP BY customer_id
HAVING AVG(days_diff) > 30;

[User] Limit the result to the top 5 customers by average days between payments in descending order.

[Assistant]
SELECT customer_id,
       AVG(days_diff) AS avg_days_between
FROM (
  SELECT p1.customer_id,
         EXTRACT(DAY FROM p2.payment_date - p1.payment_date) AS days_diff
  FROM insurance.premium_payments p1
  JOIN insurance.premium_payments p2
    ON p1.customer_id = p2.customer_id
   AND p2.payment_date > p1.payment_date
  WHERE p1.status = 'Completed'
    AND p2.status = 'Completed'
) AS t
GROUP BY customer_id
HAVING AVG(days_diff) > 30
ORDER BY avg_days_between DESC
LIMIT 5;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE token_basic_info ( coin_id character varying(100) NOT NULL, -- the id of the token token_name character varying(100) NOT NULL, -- the token's name token_symbol character varying(100) NOT NULL, -- the token's symbol token_address character varying(100) NOT NULL, -- the token's address chain text, -- the chain that the token resides price double precision, -- the current price of the token price_change_percentage_1h double precision, -- change in value divided by the absolute price value of the original token price in 1 hour price_change_percentage_24h double precision, -- change in value divided by the absolute price value of the original token price in 24 hours price_change_percentage_7d double precision, -- change in value divided by the absolute price value of the original token price in 7 days highest_price_24h double precision, -- the highest price of the token in 24 hours lowest_price_24h double precision,  -- the lowest price of the token in 24 hours market_cap double precision, -- the market cap of the token market_cap_rank bigint, -- the rank of the token market cap in desc market_cap_change_percentage_24h text, -- the percentage of market cap changes in 24 hours total_volume text, -- the trade volum of the token both in decentralized exchange(DEX) and centralized exchange(CEX) narrative text, -- the category or narrative of the token trend_rank biging, -- the trending rank of the token, value 1 expresses the most popular token. ,PRIMARY KEY (coin_id, chain) )
CREATE TABLE narrative_info ( narrative character varying(512) NOT NULL, -- the id of narrative top_3_coins text, -- the top 3 tokens in the narrative price_change_percentage_1h double precision, -- change in value divided by the absolute price value of the original token price in 1 hour in the narrative price_change_percentage_24h double precision, -- change in value divided by the absolute price value of the original token price in 24 hours in the narrative price_change_percentage_7d double precision, -- change in value divided by the absolute price value of the original token price in 7 days in the narrative market_cap double precision, -- the market cap of the narrative volume_24h double precision, -- the trade volume of the narrative trend_rank bigint, -- the trending rank of the narrative, value 1 expresses the most popular narrative token_num bigint, -- total token number in the narrative ,PRIMARY KEY (narrative) )
CREATE TABLE token_dexpool_info ( pair_address character varying(512) NOT NULL, -- 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 smart_money_token_performance ( token_address character varying(100) NOT NULL, -- the token's address token_symbol character varying(100), -- the tokens's symbol pnl numeric(38,2), -- the profit users made on this token net_flow numeric(38,2), -- the netflow of the token, means the money user spent minus the the money user sold of this token avg_cost numeric(38,16), -- the average cost price of user spent on this token price double precision, -- the current price of the token realized_ratio numeric(10,2), -- the ratio user sold of the token roi numeric(10,2), -- the roi users made of this token chain character varying(100), -- the chain that the token resides PRIMARY KEY (token_address, chain) )

[User] Which narratives saw the highest average net flow from smart money performance this year, and what is the average roi for those narratives along with the total number of tokens in each?

[Assistant]
SELECT tbi.narrative, AVG(smtp.net_flow) AS avg_net_flow, AVG(smtp.roi) AS avg_roi, COUNT(DISTINCT smtp.token_address) AS token_count
FROM smart_money_token_performance smtp
JOIN token_basic_info tbi ON smtp.token_address = tbi.token_address AND smtp.chain = tbi.chain
WHERE DATE_PART('year', CURRENT_DATE) = DATE_PART('year', CURRENT_DATE)
GROUP BY tbi.narrative
ORDER BY avg_net_flow DESC;

[User] Could you restrict the results to only those narratives with an average net flow above 5000 and an average roi greater than 0.3?

[Assistant]
SELECT tbi.narrative, AVG(smtp.net_flow) AS avg_net_flow, AVG(smtp.roi) AS avg_roi, COUNT(DISTINCT smtp.token_address) AS token_count
FROM smart_money_token_performance smtp
JOIN token_basic_info tbi ON smtp.token_address = tbi.token_address AND smtp.chain = tbi.chain
GROUP BY tbi.narrative
HAVING AVG(smtp.net_flow) > 5000 AND AVG(smtp.roi) > 0.3
ORDER BY avg_net_flow DESC;

[User] Actually, please also include the total pnl for each narrative in the output.

[Assistant]
SELECT tbi.narrative, AVG(smtp.net_flow) AS avg_net_flow, AVG(smtp.roi) AS avg_roi, SUM(smtp.pnl) AS total_pnl, COUNT(DISTINCT smtp.token_address) AS token_count
FROM smart_money_token_performance smtp
JOIN token_basic_info tbi ON smtp.token_address = tbi.token_address AND smtp.chain = tbi.chain
GROUP BY tbi.narrative
HAVING AVG(smtp.net_flow) > 5000 AND AVG(smtp.roi) > 0.3
ORDER BY avg_net_flow DESC;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE 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] Can you show the total quantity of all in-game items held by each player?

[Assistant]
SELECT player_id, SUM(quantity) AS total_quantity
FROM gaming_technology.player_inventory
GROUP BY player_id;

[User] I'd like to see only players whose total quantity is over 20.

[Assistant]
SELECT player_id, SUM(quantity) AS total_quantity
FROM gaming_technology.player_inventory
GROUP BY player_id
HAVING SUM(quantity) > 20;

[User] Also, can you include the number of different unique items each player owns?

[Assistant]
SELECT player_id, COUNT(DISTINCT item_id) AS unique_items, SUM(quantity) AS total_quantity
FROM gaming_technology.player_inventory
GROUP BY player_id
HAVING SUM(quantity) > 20;

[User] Order the final result by unique_items descending, then by total_quantity descending.

[Assistant]
SELECT player_id, COUNT(DISTINCT item_id) AS unique_items, SUM(quantity) AS total_quantity
FROM gaming_technology.player_inventory
GROUP BY player_id
HAVING SUM(quantity) > 20
ORDER BY unique_items DESC, total_quantity DESC;


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

[User] Show the name and city of all maintenance facility locations and include the total number of maintenance logs performed at each location.

[Assistant]
SELECT l.name, l.city, COUNT(m.log_id) AS maintenance_count
FROM transportation.locations l
LEFT JOIN transportation.maintenance_logs m ON l.location_id = m.vehicle_id
WHERE l.type = 'Maintenance Facility'
GROUP BY l.location_id, l.name, l.city;

[User] Only include maintenance facilities located in New York and order them by the number of maintenance logs in descending order.

[Assistant]
SELECT l.name, l.city, COUNT(m.log_id) AS maintenance_count
FROM transportation.locations l
LEFT JOIN transportation.maintenance_logs m ON l.location_id = m.vehicle_id
WHERE l.type = 'Maintenance Facility' AND l.state_province = 'NY'
GROUP BY l.location_id, l.name, l.city
ORDER BY maintenance_count DESC;


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

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

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

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

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

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

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

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

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


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE healthcare.patient_insurance ( patient_insurance_id.text, patient_id.text, plan_id.text, policy_number.text, group_number.text, subscriber_name.text, effective_date.date, expiration_date.date, is_primary.boolean )

[User] How many insurance policies does each subscriber have? Please display the subscriber name and policy count.

[Assistant] SELECT subscriber_name, COUNT(*) AS policy_count FROM healthcare.patient_insurance GROUP BY subscriber_name;

[User] Please include only subscribers who have more than one policy.

[Assistant] SELECT subscriber_name, COUNT(*) AS policy_count FROM healthcare.patient_insurance GROUP BY subscriber_name HAVING COUNT(*) > 1;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
// Node Label: :Station
// Properties:
//   station_id: String (Constraint: UNIQUE)
//   station_name: String
//   city: String (Index recommended)
//   state_province: String
//   country_code: String
//   address: String
//   timezone: String
//   number_of_platforms: Integer
//   created_at: DateTime
//   last_updated_at: DateTime
// Example Cypher CREATE:
// CREATE (:Station {station_id: 'station_xyz', station_name: 'Grand Central Terminal', city: 'New York', ...})
// Node Label: :Platform
// Properties:
//   platform_id: String (Constraint: UNIQUE)
//   platform_number: String
//   track_number: String
//   status: String
//   length_meters: Float
//   accessible: Boolean
// Relationship: (:Platform)-[:LOCATED_AT]->(:Station)
// Example Cypher CREATE:
// MATCH (s:Station {station_id: 'station_xyz'})
// CREATE (p:Platform {platform_id: 'plat_123', ...})-[:LOCATED_AT]->(s)
// Node Label: :Train
// Properties:
//   train_id: String (Constraint: UNIQUE)
//   train_number: String (Constraint: UNIQUE)
//   model: String
//   manufacturer: String
//   year_manufactured: Integer
//   capacity: Integer
//   status: String
//   last_maintenance_date: Date
//   next_maintenance_date: Date
// Example Cypher CREATE:
// CREATE (:Train {train_id: 'train_789', train_number: 'Acela 2151', ...})
// Node Label: :TrainCar
// Properties:
//   car_id: String (Constraint: UNIQUE)
//   car_number: String
//   car_type: String
//   class: String
//   capacity: Integer
//   features: String (Or List<String> if driver supports)
// Relationship: (:TrainCar)-[:PART_OF_TRAIN]->(:Train)
// Example Cypher CREATE:
// MATCH (t:Train {train_id: 'train_789'})
// CREATE (c:TrainCar {car_id: 'car_abc', ...})-[:PART_OF_TRAIN]->(t)
// Relationship: (:Route)-[rel:HAS_STOP]->(:Station)
// Relationship Properties on :HAS_STOP:
//   sequence_order: Integer
//   distance_from_previous_km: Float
//   typical_stop_duration_minutes: Integer
// Example Cypher CREATE:
// MATCH (r:Route {route_id: 'route_ne_corr'}), (s:Station {station_id: 'station_pvd'})
// CREATE (r)-[:HAS_STOP {sequence_order: 2, distance_from_previous_km: 70.5, ...}]->(s)
// Node Label: :Passenger
// Properties:
//   passenger_id: String (Constraint: UNIQUE)
//   first_name: String
//   last_name: String
//   email: String (Constraint: UNIQUE, if not null)
//   phone_number: String (Constraint: UNIQUE, if not null)
//   date_of_birth: Date
//   loyalty_program_id: String
//   created_at: DateTime
// Example Cypher CREATE:
// CREATE (:Passenger {passenger_id: 'pass_pqr', first_name: 'Alice', ...})
// Node Label: :Booking
// Properties:
//   booking_id: String (Constraint: UNIQUE)
//   booking_datetime: DateTime
//   status: String
//   total_price: Float
//   currency_code: String
//   special_requests: String
// Relationships:
//   (:Passenger)-[:MADE_BOOKING]->(:Booking)
//   (:Booking)-[:FOR_TRIP]->(:ScheduledTrip)
// Example Cypher CREATE:
// MATCH (p:Passenger {passenger_id: 'pass_pqr'}), (sched:ScheduledTrip {schedule_id: 'sched_1122'})
// CREATE (p)-[:MADE_BOOKING]->(b:Booking {booking_id: 'book_zyx', ...})-[:FOR_TRIP]->(sched)
// Node Label: :Staff
// Properties:
//   staff_id: String (Constraint: UNIQUE)
//   first_name: String
//   last_name: String
//   role: String
//   employee_number: String (Constraint: UNIQUE)
//   hire_date: Date
//   contact_email: String (Constraint: UNIQUE, if not null)
//   contact_phone: String
//   is_active: Boolean
// Relationship (Optional):
//   (:Staff)-[:BASED_AT]->(:Station)
// Example Cypher CREATE:
// CREATE (:Staff {staff_id: 'staff_mno', first_name: 'Bob', ...})
// OPTIONAL MATCH (s:Station {station_id: 'station_xyz'}) // If primary_station_id exists
// WITH s, staff_mno // Need to get the created staff node reference
// WHERE s IS NOT NULL
// CREATE (staff_mno)-[:BASED_AT]->(s)

[User] Can you help me find all staff members based at a specific station with station_id 'station_xyz', including the station details and platform information they are associated with?

[Assistant]
MATCH (stf:Staff)-[:BASED_AT]->(s:Station {station_id: 'station_xyz'})
OPTIONAL MATCH (p:Platform)-[:LOCATED_AT]->(s)
RETURN stf.staff_id, stf.first_name, stf.last_name, stf.role, s.station_id, s.station_name, p.platform_id, p.platform_number, p.status

[User] Can you filter the results to include only staff with the role of 'Manager' and platforms with status 'Operational'?

[Assistant]
MATCH (stf:Staff)-[:BASED_AT]->(s:Station {station_id: 'station_xyz'})
OPTIONAL MATCH (p:Platform)-[:LOCATED_AT]->(s)
WHERE stf.role = 'Manager' AND (p.status = 'Operational' OR p IS NULL)
RETURN stf.staff_id, stf.first_name, stf.last_name, stf.role, s.station_id, s.station_name, p.platform_id, p.platform_number, p.status

[User] Can you sort the results by staff last name and platform number?

[Assistant]
MATCH (stf:Staff)-[:BASED_AT]->(s:Station {station_id: 'station_xyz'})
OPTIONAL MATCH (p:Platform)-[:LOCATED_AT]->(s)
WHERE stf.role = 'Manager' AND (p.status = 'Operational' OR p IS NULL)
RETURN stf.staff_id, stf.first_name, stf.last_name, stf.role, s.station_id, s.station_name, p.platform_id, p.platform_number, p.status
ORDER BY stf.last_name, p.platform_number


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE insurance.claim_documents ( document_id text PRIMARY KEY, claim_id text, document_type text, file_name text, file_path text, file_size_bytes int, mime_type text, uploaded_by text, uploaded_at timestamp, description text )

[User] Show the top 5 largest documents by file size, including document_id, claim_id, file_name, and file_size_bytes.

[Assistant]
SELECT document_id,
       claim_id,
       file_name,
       file_size_bytes
FROM insurance.claim_documents
ORDER BY file_size_bytes DESC
LIMIT 5;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE financial_services.market_data (
    data_point_id bigserial NOT NULL, -- auto-incrementing primary key
    security_id character varying(64) NOT NULL, -- identifier for the security
    data_timestamp timestamp NOT NULL, -- timestamp for the data point (e.g., end of day, intraday)
    open_price numeric(19, 8), -- opening price for the period
    high_price numeric(19, 8), -- highest price during the period
    low_price numeric(19, 8), -- lowest price during the period
    close_price numeric(19, 8) NOT NULL, -- closing price for the period
    adjusted_close_price numeric(19, 8), -- closing price adjusted for dividends and splits
    volume bigint, -- trading volume during the period
    source character varying(50), -- source of the market data (e.g., Bloomberg, Refinitiv)
    PRIMARY KEY (data_point_id),
    UNIQUE (security_id, data_timestamp), -- Ensure unique data point per security per time
    FOREIGN KEY (security_id) REFERENCES financial_services.securities(security_id)
)

[User] For each security sector, what is the average volume recorded in the market data?

[Assistant] SELECT T2.sector, AVG(T1.volume) FROM financial_services.market_data AS T1 JOIN financial_services.securities AS T2 ON T1.security_id = T2.security_id GROUP BY T2.sector;

[User] Can you restrict this to data points from the last 6 months?

[Assistant] SELECT T2.sector, AVG(T1.volume) FROM financial_services.market_data AS T1 JOIN financial_services.securities AS T2 ON T1.security_id = T2.security_id WHERE T1.data_timestamp >= NOW() - INTERVAL '6 months' GROUP BY T2.sector;

[User] Also include the count of data points per sector in the result.

[Assistant] SELECT T2.sector, AVG(T1.volume), COUNT(T1.data_point_id) FROM financial_services.market_data AS T1 JOIN financial_services.securities AS T2 ON T1.security_id = T2.security_id WHERE T1.data_timestamp >= NOW() - INTERVAL '6 months' GROUP BY T2.sector;

[User] Filter out sectors with fewer than 1000 data points in this period.

[Assistant] SELECT T2.sector, AVG(T1.volume), COUNT(T1.data_point_id) FROM financial_services.market_data AS T1 JOIN financial_services.securities AS T2 ON T1.security_id = T2.security_id WHERE T1.data_timestamp >= NOW() - INTERVAL '6 months' GROUP BY T2.sector HAVING COUNT(T1.data_point_id) >= 1000;


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

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

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


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE social_media.comments (
    comment_id character varying(64) NOT NULL, -- unique identifier for the comment
    post_id character varying(64) NOT NULL, -- identifier of the post being commented on (FK to posts.post_id)
    user_id character varying(64) NOT NULL, -- identifier of the user who made the comment (FK to users.user_id)
    parent_comment_id character varying(64), -- identifier of the parent comment if it's a reply (FK to comments.comment_id)
    content text NOT NULL, -- textual content of the comment
    created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, -- timestamp of comment creation
    updated_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, -- timestamp of last comment edit
    PRIMARY KEY (comment_id)
)

[User] Count the number of comments that have been updated since they were first created.

[Assistant] SELECT COUNT(*) FROM social_media.comments WHERE updated_at > created_at;


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

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

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

[User] Now exclude any games released before 2018.

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

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

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


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE gaming_technology.games ( game_id uuid PRIMARY KEY, title text, developer_id uuid, publisher_id uuid, genre text, release_date date, description text, platform text, engine text, website text )
CREATE TABLE gaming_technology.developers ( developer_id.uuid, name.text, country.text, founded_year.integer, website.text, created_at.timestamptz )
CREATE TABLE gaming_technology.game_sessions ( session_id uuid NOT NULL DEFAULT gen_random_uuid(), player_id uuid NOT NULL, game_id uuid NOT NULL, server_id uuid, start_time timestamp with time zone NOT NULL DEFAULT CURRENT_TIMESTAMP, end_time timestamp with time zone, duration_seconds integer, score integer, session_data jsonb, PRIMARY KEY (session_id) )

[User] Which games were developed by companies in 'United Kingdom'? List the game title and the developer's name.

[Assistant] SELECT T1.title, T2.name FROM gaming_technology.games AS T1 JOIN gaming_technology.developers AS T2 ON T1.developer_id = T2.developer_id WHERE T2.country = 'United Kingdom';

[User] For these games, what is the total duration of all game sessions played? Show game title and total duration in seconds.

[Assistant] SELECT T1.title, SUM(T3.duration_seconds) AS total_duration FROM gaming_technology.games AS T1 JOIN gaming_technology.developers AS T2 ON T1.developer_id = T2.developer_id JOIN gaming_technology.game_sessions AS T3 ON T1.game_id = T3.game_id WHERE T2.country = 'United Kingdom' GROUP BY T1.title;

[User] Only include games where the total session duration is more than 1000000 seconds.

[Assistant] SELECT T1.title, SUM(T3.duration_seconds) AS total_duration FROM gaming_technology.games AS T1 JOIN gaming_technology.developers AS T2 ON T1.developer_id = T2.developer_id JOIN gaming_technology.game_sessions AS T3 ON T1.game_id = T3.game_id WHERE T2.country = 'United Kingdom' GROUP BY T1.title HAVING SUM(T3.duration_seconds) > 1000000;

[User] Order the results by total duration in descending order and limit to the top 5.

[Assistant] SELECT T1.title, SUM(T3.duration_seconds) AS total_duration FROM gaming_technology.games AS T1 JOIN gaming_technology.developers AS T2 ON T1.developer_id = T2.developer_id JOIN gaming_technology.game_sessions AS T3 ON T1.game_id = T3.game_id WHERE T2.country = 'United Kingdom' GROUP BY T1.title HAVING SUM(T3.duration_seconds) > 1000000 ORDER BY total_duration DESC LIMIT 5;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE gaming_technology.player_achievements ( player_achievement_id.uuid, player_id.uuid, achievement_id.uuid, unlocked_at.timestamptz )

[User] List each player's most recent achievement unlock, showing the player_id, achievement_id, and unlocked_at timestamp.

[Assistant] SELECT pa.player_id, pa.achievement_id, pa.unlocked_at FROM gaming_technology.player_achievements pa INNER JOIN (SELECT player_id, MAX(unlocked_at) AS max_unlocked FROM gaming_technology.player_achievements GROUP BY player_id) sub ON pa.player_id = sub.player_id AND pa.unlocked_at = sub.max_unlocked;

[User] I got duplicate rows for some players who unlocked multiple achievements at the exact same time. Can you make sure to include all such achievements for the player, but if that's the case, list one row per achievement?

[Assistant] SELECT pa.player_id, pa.achievement_id, pa.unlocked_at FROM gaming_technology.player_achievements pa INNER JOIN (SELECT player_id, MAX(unlocked_at) AS max_unlocked FROM gaming_technology.player_achievements GROUP BY player_id) sub ON pa.player_id = sub.player_id AND pa.unlocked_at = sub.max_unlocked;

[User] Instead, for each player, just show the total number of achievements unlocked on their most recent unlock timestamp.

[Assistant] SELECT pa.player_id, pa.unlocked_at AS most_recent_unlocked_at, COUNT(*) AS achievements_on_latest_time FROM gaming_technology.player_achievements pa INNER JOIN (SELECT player_id, MAX(unlocked_at) AS max_unlocked FROM gaming_technology.player_achievements GROUP BY player_id) sub ON pa.player_id = sub.player_id AND pa.unlocked_at = sub.max_unlocked GROUP BY pa.player_id, pa.unlocked_at;

[User] Now filter to only show players where achievements_on_latest_time is greater than 1.

[Assistant] SELECT pa.player_id, pa.unlocked_at AS most_recent_unlocked_at, COUNT(*) AS achievements_on_latest_time FROM gaming_technology.player_achievements pa INNER JOIN (SELECT player_id, MAX(unlocked_at) AS max_unlocked FROM gaming_technology.player_achievements GROUP BY player_id) sub ON pa.player_id = sub.player_id AND pa.unlocked_at = sub.max_unlocked GROUP BY pa.player_id, pa.unlocked_at HAVING COUNT(*) > 1;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE healthcare.doctors ( doctor_id text PRIMARY KEY, first_name text, last_name text, specialty text, license_number text, phone_number text, email text, hospital_affiliation_id text, created_at timestamp, updated_at timestamp )
CREATE TABLE healthcare.diagnoses ( diagnosis_id character varying(64) NOT NULL, record_id character varying(64) NOT NULL, patient_id character varying(64) NOT NULL, doctor_id character varying(64) NOT NULL, diagnosis_code character varying(20) NOT NULL, code_type character varying(10) NOT NULL DEFAULT 'ICD-10', description text, diagnosis_date date NOT NULL, status character varying(32) NOT NULL, is_chronic boolean DEFAULT false, PRIMARY KEY (diagnosis_id) )
CREATE TABLE healthcare.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 distinct patient IDs who have received a diagnosis from a doctor with 'Cardiology' specialty.

[Assistant] SELECT DISTINCT T1.patient_id FROM healthcare.diagnoses AS T1 JOIN healthcare.doctors AS T2 ON T1.doctor_id = T2.doctor_id WHERE T2.specialty = 'Cardiology';

[User] For these patients, also show their primary insurance policy number.

[Assistant] SELECT DISTINCT T1.patient_id, T3.policy_number FROM healthcare.diagnoses AS T1 JOIN healthcare.doctors AS T2 ON T1.doctor_id = T2.doctor_id JOIN healthcare.patient_insurance AS T3 ON T1.patient_id = T3.patient_id WHERE T2.specialty = 'Cardiology' AND T3.is_primary = true;

[User] Only include patients whose 'Cardiology' diagnosis was made in the last year.

[Assistant] SELECT DISTINCT T1.patient_id, T3.policy_number FROM healthcare.diagnoses AS T1 JOIN healthcare.doctors AS T2 ON T1.doctor_id = T2.doctor_id JOIN healthcare.patient_insurance AS T3 ON T1.patient_id = T3.patient_id WHERE T2.specialty = 'Cardiology' AND T3.is_primary = true AND T1.diagnosis_date >= date('now', '-1 year');


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

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

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

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

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


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE government_services.citizens ( citizen_id text PRIMARY KEY, national_id_number text, first_name text, last_name text, date_of_birth date, gender text, primary_address text, contact_email text, contact_phone text, registration_date timestamp, is_verified boolean )
CREATE TABLE government_services.agencies ( agency_id text PRIMARY KEY, agency_name text, jurisdiction_level text, primary_contact_email text, main_phone_number text, website_url text, established_date date, parent_agency_id text )
CREATE TABLE government_services.services ( service_id text PRIMARY KEY, agency_id text, service_name text, description text, category text, eligibility_criteria text, standard_fee numeric, average_processing_time_days int, is_active boolean, online_application_url text )
CREATE TABLE government_services.employees ( employee_id text PRIMARY KEY, agency_id text, first_name text, last_name text, job_title text, department text, work_email text, work_phone text, hire_date date, termination_date date, access_level text, manager_employee_id text )
CREATE TABLE government_services.service_locations ( location_id text PRIMARY KEY, agency_id text, location_name text, address text, city text, state text, postal_code text, latitude numeric, longitude numeric, operating_hours text, contact_phone text, is_accessible boolean )
CREATE TABLE government_services.appointments ( appointment_id text PRIMARY KEY, citizen_id text, employee_id text, location_id text, service_id text, scheduled_start_time timestamp, scheduled_end_time timestamp, purpose text, status text, booking_method text, created_at timestamp, notes text )
CREATE TABLE government_services.notifications ( notification_id text PRIMARY KEY, citizen_id text, application_id text, message_subject text, message_body text, channel text, sent_at timestamp, status text, related_entity_type text, related_entity_id text )

[User] Retrieve each agency’s name along with the count of accessible service locations it has in California.

[Assistant]
SELECT
  a.agency_name,
  COUNT(l.location_id) AS accessible_location_count
FROM government_services.agencies a
JOIN government_services.service_locations l
  ON a.agency_id = l.agency_id
WHERE l.is_accessible = TRUE
  AND l.state = 'California'
GROUP BY a.agency_name;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE legal_services.clients ( client_id text, first_name text, last_name text, company_name text, email text, phone text, address text, date_registered timestamp, status text )
CREATE TABLE legal_services.lawyers ( lawyer_id text, first_name text, last_name text, bar_number text, firm_id text, email text, phone text, specialization text, hire_date timestamp, is_partner boolean )

[User] Find all clients and lawyers who share the same phone area code, and show each client's first and last name, each lawyer's first and last name, and the shared area code.

[Assistant] SELECT c.first_name AS client_first_name, c.last_name AS client_last_name, l.first_name AS lawyer_first_name, l.last_name AS lawyer_last_name, SUBSTRING(c.phone, 1, 3) AS area_code FROM legal_services.clients c JOIN legal_services.lawyers l ON SUBSTRING(c.phone, 1, 3) = SUBSTRING(l.phone, 1, 3);


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

[User] List every offline server alongside an online server in the same region. Show offline_server and online_server names.

[Assistant]
SELECT o.server_name AS online_server, f.server_name AS offline_server
FROM gaming_technology.servers f
JOIN gaming_technology.servers o
  ON f.region = o.region
WHERE f.status = 'offline'
  AND o.status = 'online';

[User] Include the online server's current_players and status in the result.

[Assistant]
SELECT o.server_name AS online_server, o.current_players, o.status, f.server_name AS offline_server
FROM gaming_technology.servers f
JOIN gaming_technology.servers o
  ON f.region = o.region
WHERE f.status = 'offline'
  AND o.status = 'online';

[User] Only include pairs where the offline server's last_heartbeat was more than 30 minutes ago.

[Assistant]
SELECT o.server_name AS online_server, o.current_players, o.status, f.server_name AS offline_server
FROM gaming_technology.servers f
JOIN gaming_technology.servers o
  ON f.region = o.region
WHERE f.status = 'offline'
  AND o.status = 'online'
  AND f.last_heartbeat < NOW() - INTERVAL '30 minutes';

[User] Sort the result by the offline_server name ascending.

[Assistant]
SELECT o.server_name AS online_server, o.current_players, o.status, f.server_name AS offline_server
FROM gaming_technology.servers f
JOIN gaming_technology.servers o
  ON f.region = o.region
WHERE f.status = 'offline'
  AND o.status = 'online'
  AND f.last_heartbeat < NOW() - INTERVAL '30 minutes'
ORDER BY f.server_name ASC;


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

[User] List each participant_id along with the total number of participants in their conversation, and include user_id and conversation_id.

[Assistant]
SELECT cp.participant_id, cp.user_id, cp.conversation_id, counts.participant_count
FROM social_media.conversation_participants cp
JOIN (
  SELECT conversation_id, COUNT(*) AS participant_count
  FROM social_media.conversation_participants
  GROUP BY conversation_id
) counts ON cp.conversation_id = counts.conversation_id;

[User] Actually, only include conversations where the participant_count is greater than 2.

[Assistant]
SELECT cp.participant_id, cp.user_id, cp.conversation_id, counts.participant_count
FROM social_media.conversation_participants cp
JOIN (
  SELECT conversation_id, COUNT(*) AS participant_count
  FROM social_media.conversation_participants
  GROUP BY conversation_id
  HAVING COUNT(*) > 2
) counts ON cp.conversation_id = counts.conversation_id;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE government_services.agencies ( agency_id character varying(64) NOT NULL, agency_name character varying(255) NOT NULL, jurisdiction_level character varying(50) NOT NULL, 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), PRIMARY KEY (agency_id) )
CREATE TABLE government_services.appointments ( appointment_id character varying(64) NOT NULL, citizen_id character varying(64) NOT NULL, employee_id character varying(64), location_id character varying(64), service_id character varying(64), scheduled_start_time timestamp NOT NULL, scheduled_end_time timestamp, purpose text NOT NULL, status character varying(30) NOT NULL, booking_method character varying(50), created_at timestamp NOT NULL, notes text, PRIMARY KEY (appointment_id) )

[User] List the name of each agency and the number of appointments associated with services from that agency.

[Assistant] SELECT T1.agency_name, COUNT(T2.appointment_id) FROM agencies AS T1 JOIN appointments AS T2 ON T1.agency_id = T2.agency_id GROUP BY T1.agency_name;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE government_services.citizens (
    citizen_id character varying(64) NOT NULL,  -- unique identifier for the citizen
    national_id_number character varying(128) NOT NULL UNIQUE, -- official national identification number
    first_name character varying(100) NOT NULL,
    last_name character varying(100) NOT NULL,
    date_of_birth date NOT NULL,
    gender character varying(20),
    primary_address text NOT NULL, -- full primary residential address
    contact_email character varying(128) UNIQUE,
    contact_phone character varying(32),
    registration_date timestamp NOT NULL, -- when the citizen profile was created
    is_verified boolean DEFAULT false, -- whether identity has been officially verified
    PRIMARY KEY (citizen_id)
)
CREATE TABLE government_services.services ( service_id character varying(64) NOT NULL, agency_id character varying(64) NOT NULL, service_name character varying(255) NOT NULL, description text, category character varying(100), eligibility_criteria text, standard_fee numeric(10, 2) DEFAULT 0.00, average_processing_time_days integer, is_active boolean DEFAULT true, online_application_url character varying(255), PRIMARY KEY (service_id) )
CREATE TABLE government_services.applications ( application_id character varying(64) NOT NULL, citizen_id character varying(64) NOT NULL, service_id character varying(64) NOT NULL, submitted_at timestamp NOT NULL, status character varying(50) NOT NULL, last_updated_at timestamp NOT NULL, assigned_employee_id character varying(64), decision_date date, notes text, reference_number character varying(100) UNIQUE, PRIMARY KEY (application_id) )
CREATE TABLE government_services.documents ( document_id text, application_id text, citizen_id text, document_type text, file_reference text, upload_timestamp timestamp, expiry_date date, verification_status text, verified_by_employee_id text, verification_timestamp timestamp )
CREATE TABLE government_services.payments ( payment_id text, application_id text, citizen_id text, service_id text, amount numeric, currency text, payment_method text, payment_provider_reference text, payment_timestamp timestamp, status text, notes text )
CREATE TABLE government_services.employees ( employee_id character varying(64) NOT NULL, agency_id character varying(64) NOT NULL, first_name character varying(100) NOT NULL, last_name character varying(100) NOT NULL, job_title character varying(150) NOT NULL, department character varying(100), work_email character varying(128) NOT NULL UNIQUE, work_phone character varying(32), hire_date date NOT NULL, termination_date date, access_level character varying(50), manager_employee_id character varying(64), PRIMARY KEY (employee_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)
)
CREATE TABLE government_services.appointments ( appointment_id text PRIMARY KEY, citizen_id text, employee_id text, location_id text, service_id text, scheduled_start_time timestamp, scheduled_end_time timestamp, purpose text, status text, booking_method text, created_at timestamp, notes text )
CREATE TABLE government_services.notifications ( notification_id character varying(64) NOT NULL, citizen_id character varying(64) NOT NULL, application_id character varying(64), message_subject character varying(255), message_body text NOT NULL, channel character varying(30) NOT NULL, sent_at timestamp NOT NULL, status character varying(30) NOT NULL, related_entity_type character varying(50), related_entity_id character varying(64), PRIMARY KEY (notification_id) )

[User] Find all citizens who have both uploaded at least one document and made at least one payment. Show their citizen ID, full name, and contact email.

[Assistant]
SELECT c.citizen_id, c.first_name || ' ' || c.last_name AS full_name, c.contact_email
FROM government_services.citizens c
WHERE EXISTS (
    SELECT 1 FROM government_services.documents d WHERE d.citizen_id = c.citizen_id
) AND EXISTS (
    SELECT 1 FROM government_services.payments p WHERE p.citizen_id = c.citizen_id
);


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE hospitality_technology.service_orders ( order_id text PRIMARY KEY, reservation_id text, guest_id text, service_id text, staff_id_ordered text, staff_id_delivered text, order_timestamp timestamp, delivery_timestamp timestamp, quantity int, unit_price numeric, total_price numeric, status text, notes text, bill_id text )

[User] Show the total revenue and the average order value for each order status.

[Assistant] SELECT status, SUM(total_price) AS total_revenue, AVG(total_price) AS avg_order_value FROM hospitality_technology.service_orders GROUP BY status;

[User] Please only include statuses where the total revenue is above 1000.

[Assistant] SELECT status, SUM(total_price) AS total_revenue, AVG(total_price) AS avg_order_value FROM hospitality_technology.service_orders GROUP BY status HAVING SUM(total_price) > 1000;

[User] Also order the results by total revenue descending.

[Assistant] SELECT status, SUM(total_price) AS total_revenue, AVG(total_price) AS avg_order_value FROM hospitality_technology.service_orders GROUP BY status HAVING SUM(total_price) > 1000 ORDER BY total_revenue DESC;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE project_fundraising_record ( id text, project_id text, project_name text, rounds_name text, investment_value numeric, investment_date text, introduction text, valuation numeric )
CREATE TABLE token_basic_info ( coin_id text, token_name text, token_symbol text, token_address text, chain text, price numeric, price_change_percentage_1h numeric, price_change_percentage_24h numeric, price_change_percentage_7d numeric, highest_price_24h numeric, lowest_price_24h numeric, market_cap numeric, market_cap_rank numeric, market_cap_change_percentage_24h text, total_volume text, narrative text, trend_rank numeric )
CREATE TABLE narrative_info ( narrative text, top_3_coins text, price_change_percentage_1h numeric, price_change_percentage_24h numeric, price_change_percentage_7d numeric, market_cap numeric, volume_24h numeric, trend_rank numeric, token_num numeric )
CREATE TABLE token_dexpool_info ( pair_address text, token_name text, token_symbol text, chain text, price numeric, price_change_percentage_1h numeric, price_change_percentage_6h numeric, price_change_percentage_24h numeric, makers_24h numeric, volume_24h numeric, liquidity numeric, market_cap numeric, trend_rank numeric )
CREATE TABLE smart_money_token_performance ( token_address text, token_symbol text, pnl numeric, net_flow numeric, avg_cost numeric, price numeric, realized_ratio numeric, roi numeric, chain text )

[User] For each narrative in token_basic_info, calculate the total net_flow and average ROI from smart_money_token_performance. List narrative, total_net_flow, avg_roi, ordered by total_net_flow descending.

[Assistant]
SELECT tbi.narrative,
       SUM(smtp.net_flow) AS total_net_flow,
       AVG(smtp.roi) AS avg_roi
FROM token_basic_info tbi
JOIN smart_money_token_performance smtp
  ON tbi.token_address = smtp.token_address
GROUP BY tbi.narrative
ORDER BY total_net_flow DESC;

[User] Now only show narratives with avg_roi greater than 0.10 and total_net_flow positive.

[Assistant]
SELECT tbi.narrative,
       SUM(smtp.net_flow) AS total_net_flow,
       AVG(smtp.roi) AS avg_roi
FROM token_basic_info tbi
JOIN smart_money_token_performance smtp
  ON tbi.token_address = smtp.token_address
GROUP BY tbi.narrative
HAVING SUM(smtp.net_flow) > 0
   AND AVG(smtp.roi) > 0.10
ORDER BY total_net_flow DESC;

[User] Also include the number of unique tokens contributing to each narrative as token_count.

[Assistant]
SELECT tbi.narrative,
       SUM(smtp.net_flow) AS total_net_flow,
       AVG(smtp.roi) AS avg_roi,
       COUNT(DISTINCT tbi.token_address) AS token_count
FROM token_basic_info tbi
JOIN smart_money_token_performance smtp
  ON tbi.token_address = smtp.token_address
GROUP BY tbi.narrative
HAVING SUM(smtp.net_flow) > 0
   AND AVG(smtp.roi) > 0.10
ORDER BY total_net_flow DESC;

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

[Assistant]
SELECT tbi.narrative,
       SUM(smtp.net_flow) AS total_net_flow,
       AVG(smtp.roi) AS avg_roi,
       COUNT(DISTINCT tbi.token_address) AS token_count
FROM token_basic_info tbi
JOIN smart_money_token_performance smtp
  ON tbi.token_address = smtp.token_address
GROUP BY tbi.narrative
HAVING SUM(smtp.net_flow) > 0
   AND AVG(smtp.roi) > 0.10
ORDER BY total_net_flow DESC
LIMIT 5;


[User] Get me all unbilled billable time entries with their entry_id, case_id, lawyer_id, hours_spent, and billing_rate.

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

[User] Actually, I only want entries for lawyer 'lawyer_123'.

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

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

[Assistant]
SELECT entry_id,
       case_id,
       lawyer_id,
       hours_spent,
       billing_rate
FROM legal_services.time_entries
WHERE is_billable = TRUE
  AND is_billed = FALSE
  AND lawyer_id = 'lawyer_123'
ORDER BY hours_spent DESC;


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

[User] List the record ID, record date, patient ID, and chief complaint for medical records belonging to patients whose last name is 'Smith'. Also include the patient's last name in the results.

[Assistant] SELECT mr.record_id, mr.record_date, mr.patient_id, mr.chief_complaint, p.last_name FROM healthcare.medical_records mr JOIN patients p ON mr.patient_id = p.patient_id WHERE p.last_name = 'Smith';

[User] Refine this list to only show records where the record date is in 2024 and the chief complaint is not null. Sort by record_date in ascending order.

[Assistant] SELECT mr.record_id, mr.record_date, mr.patient_id, mr.chief_complaint, p.last_name FROM healthcare.medical_records mr JOIN patients p ON mr.patient_id = p.patient_id WHERE p.last_name = 'Smith' AND EXTRACT(YEAR FROM mr.record_date) = 2024 AND (mr.chief_complaint IS NOT NULL AND mr.chief_complaint != '') ORDER BY mr.record_date ASC;


[User] List all time entries where the description includes the word 'email', showing the entry ID, date worked, hours spent, and description.

[Assistant] SELECT entry_id, date_worked, hours_spent, description FROM legal_services.time_entries WHERE description ILIKE '%email%';


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE social_media.users ( user_id text, username text, email text, password_hash text, full_name text, profile_picture_url text, bio text, location text, created_at timestamp, updated_at timestamp, is_verified boolean )
CREATE TABLE social_media.posts ( post_id.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.post_hashtags ( post_hashtag_id character varying(64) NOT NULL, post_id character varying(64) NOT NULL, hashtag_id character varying(64) NOT NULL, PRIMARY KEY (post_hashtag_id), CONSTRAINT unique_post_hashtag UNIQUE (post_id, hashtag_id) )
CREATE TABLE social_media.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
)

[User] Show me all users along with the total number of unique hashtags used in their posts.

[Assistant]
SELECT u.user_id, u.username, COUNT(DISTINCT ph.hashtag_id) AS unique_hashtag_count
FROM social_media.users u
LEFT JOIN social_media.posts p ON u.user_id = p.user_id
LEFT JOIN social_media.post_hashtags ph ON p.post_id = ph.post_id
GROUP BY u.user_id, u.username;

[User] Can you include only the users who have used more than 2 unique hashtags?

[Assistant]
SELECT u.user_id, u.username, COUNT(DISTINCT ph.hashtag_id) AS unique_hashtag_count
FROM social_media.users u
LEFT JOIN social_media.posts p ON u.user_id = p.user_id
LEFT JOIN social_media.post_hashtags ph ON p.post_id = ph.post_id
GROUP BY u.user_id, u.username
HAVING COUNT(DISTINCT ph.hashtag_id) > 2;


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

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

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

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

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

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

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

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

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


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE social_media.users (
    user_id character varying(64) NOT NULL,  -- unique identifier for the user
    username character varying(50) NOT NULL UNIQUE, -- user's unique handle
    email character varying(128) NOT NULL UNIQUE, -- user's email address
    password_hash text NOT NULL, -- hashed password
    full_name character varying(100), -- user's full name
    profile_picture_url text, -- URL to the profile picture
    bio text, -- short user biography
    location character varying(100), -- user's location
    created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, -- timestamp of account creation
    updated_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, -- timestamp of last profile update
    is_verified boolean NOT NULL DEFAULT false, -- verification status
    PRIMARY KEY (user_id)
)
CREATE TABLE social_media.hashtags ( hashtag_id character varying(64) NOT NULL, tag_name character varying(100) NOT NULL UNIQUE, created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, PRIMARY KEY (hashtag_id) )
CREATE TABLE social_media.post_hashtags ( post_hashtag_id character varying(64) NOT NULL, post_id character varying(64) NOT NULL, hashtag_id character varying(64) NOT NULL, PRIMARY KEY (post_hashtag_id), CONSTRAINT unique_post_hashtag UNIQUE (post_id, hashtag_id) )
CREATE TABLE social_media.messages ( message_id character varying(64) NOT NULL, conversation_id character varying(64) NOT NULL, sender_user_id character varying(64) NOT NULL, content text, media_url text, media_type character varying(20), sent_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, read_at timestamp, PRIMARY KEY (message_id) )
CREATE TABLE social_media.conversations ( conversation_id text PRIMARY KEY, created_at timestamp, last_message_at timestamp, is_group_chat bool, group_name text )
CREATE TABLE social_media.notifications ( notification_id text PRIMARY KEY, recipient_user_id text, sender_user_id text, notification_type text, target_entity_id text, target_entity_type text, created_at timestamp, read_at timestamp )
CREATE TABLE social_media.user_settings ( setting_id text, user_id text, theme text, email_notifications_enabled boolean, push_notifications_enabled boolean, private_profile boolean, updated_at timestamp )

[User] Show me for each user how many conversations they've participated in, include their email and conversation count, only for those who have participated in more than five conversations.

[Assistant]
SELECT u.user_id, u.email, COUNT(DISTINCT m.conversation_id) AS conversation_count
FROM social_media.messages m
JOIN social_media.users u ON m.sender_user_id = u.user_id
GROUP BY u.user_id, u.email
HAVING COUNT(DISTINCT m.conversation_id) > 5;

[User] Actually, I only want to count group chats.

[Assistant]
SELECT u.user_id, u.email, COUNT(DISTINCT m.conversation_id) AS conversation_count
FROM social_media.messages m
JOIN social_media.conversations c ON m.conversation_id = c.conversation_id
JOIN social_media.users u ON m.sender_user_id = u.user_id
WHERE c.is_group_chat = true
GROUP BY u.user_id, u.email
HAVING COUNT(DISTINCT m.conversation_id) > 5;


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

[User] List all in-game items' names, types, and rarity along with their total cost in USD, for items that belong to games released on or after 2021-01-01.

[Assistant]
SELECT i.item_name, i.item_type, i.rarity, i.cost_amount
FROM gaming_technology.in_game_items i
JOIN gaming_technology.games g ON i.game_id = g.game_id
WHERE g.release_date >= '2021-01-01' AND i.cost_currency = 'USD'
ORDER BY i.item_name;

[User] Please add the game's title to the results.

[Assistant]
SELECT i.item_name, i.item_type, i.rarity, i.cost_amount, g.title AS game_title
FROM gaming_technology.in_game_items i
JOIN gaming_technology.games g ON i.game_id = g.game_id
WHERE g.release_date >= '2021-01-01' AND i.cost_currency = 'USD'
ORDER BY i.item_name;

[User] Now, show only items of rarity 'Epic' or 'Legendary'.

[Assistant]
SELECT i.item_name, i.item_type, i.rarity, i.cost_amount, g.title AS game_title
FROM gaming_technology.in_game_items i
JOIN gaming_technology.games g ON i.game_id = g.game_id
WHERE g.release_date >= '2021-01-01' AND i.cost_currency = 'USD' AND i.rarity IN ('Epic', 'Legendary')
ORDER BY i.item_name;

[User] I got an error because some items have null cost_amount. Can you exclude those from the results?

[Assistant]
SELECT i.item_name, i.item_type, i.rarity, i.cost_amount, g.title AS game_title
FROM gaming_technology.in_game_items i
JOIN gaming_technology.games g ON i.game_id = g.game_id
WHERE g.release_date >= '2021-01-01' AND i.cost_currency = 'USD' AND i.rarity IN ('Epic', 'Legendary') AND i.cost_amount IS NOT NULL
ORDER BY i.item_name;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE gaming_technology.servers ( server_id uuid NOT NULL DEFAULT gen_random_uuid(), game_id uuid NOT NULL, server_name character varying(150), region character varying(50) NOT NULL, ip_address character varying(45), port integer, current_players integer NOT NULL DEFAULT 0, max_players integer NOT NULL, status character varying(30) NOT NULL DEFAULT 'offline', last_heartbeat timestamp with time zone, PRIMARY KEY (server_id) )

[User] For each server, show it alongside another server in the same region that has the closest number of current players.

[Assistant]
SELECT
  s1.server_id AS server_a_id,
  s1.server_name AS server_a_name,
  s2.server_id AS server_b_id,
  s2.server_name AS server_b_name,
  ABS(s1.current_players - s2.current_players) AS player_diff
FROM gaming_technology.servers s1
JOIN gaming_technology.servers s2
  ON s1.region = s2.region
  AND s1.server_id <> s2.server_id
ORDER BY s1.server_id, player_diff
LIMIT 1;

[User] Actually, restrict both servers to those that are currently online.

[Assistant]
SELECT
  s1.server_id AS server_a_id,
  s1.server_name AS server_a_name,
  s2.server_id AS server_b_id,
  s2.server_name AS server_b_name,
  ABS(s1.current_players - s2.current_players) AS player_diff
FROM gaming_technology.servers s1
JOIN gaming_technology.servers s2
  ON s1.region = s2.region
  AND s1.server_id <> s2.server_id
WHERE s1.status = 'online'
  AND s2.status = 'online'
ORDER BY s1.server_id, player_diff
LIMIT 1;

[User] Finally, only show pairs where the difference in current players is less than 10.

[Assistant]
SELECT
  s1.server_id AS server_a_id,
  s1.server_name AS server_a_name,
  s2.server_id AS server_b_id,
  s2.server_name AS server_b_name,
  ABS(s1.current_players - s2.current_players) AS player_diff
FROM gaming_technology.servers s1
JOIN gaming_technology.servers s2
  ON s1.region = s2.region
  AND s1.server_id <> s2.server_id
WHERE s1.status = 'online'
  AND s2.status = 'online'
  AND ABS(s1.current_players - s2.current_players) < 10
ORDER BY s1.server_id, player_diff;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE social_media.users (
    user_id character varying(64) NOT NULL,  -- unique identifier for the user
    username character varying(50) NOT NULL UNIQUE, -- user's unique handle
    email character varying(128) NOT NULL UNIQUE, -- user's email address
    password_hash text NOT NULL, -- hashed password
    full_name character varying(100), -- user's full name
    profile_picture_url text, -- URL to the profile picture
    bio text, -- short user biography
    location character varying(100), -- user's location
    created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, -- timestamp of account creation
    updated_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, -- timestamp of last profile update
    is_verified boolean NOT NULL DEFAULT false, -- verification status
    PRIMARY KEY (user_id)
)
CREATE TABLE social_media.posts (
    post_id character varying(64) NOT NULL, -- unique identifier for the post
    user_id character varying(64) NOT NULL, -- identifier of the user who created the post (FK to users.user_id)
    content text, -- textual content of the post
    media_url text, -- URL to attached media (image/video)
    media_type character varying(20), -- type of media ('image', 'video', null)
    created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, -- timestamp of post creation
    updated_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, -- timestamp of last post edit
    visibility character varying(20) NOT NULL DEFAULT 'public', -- visibility ('public', 'friends', 'private')
    location_lat numeric(9,6), -- latitude of post location
    location_lon numeric(9,6), -- longitude of post location
    PRIMARY KEY (post_id)
)
CREATE TABLE social_media.likes (
    like_id character varying(64) NOT NULL, -- unique identifier for the like
    user_id character varying(64) NOT NULL, -- identifier of the user who liked (FK to users.user_id)
    post_id character varying(64), -- identifier of the post being liked (FK to posts.post_id, nullable)
    comment_id character varying(64), -- identifier of the comment being liked (FK to comments.comment_id, nullable)
    created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, -- timestamp of when the like occurred
    PRIMARY KEY (like_id),
    CONSTRAINT unique_user_like UNIQUE (user_id, post_id, comment_id), -- prevent duplicate likes
    CONSTRAINT check_like_target CHECK (post_id IS NOT NULL OR comment_id IS NOT NULL) -- ensure it likes something
)
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.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 character varying(64) NOT NULL, -- unique identifier for the conversation
    created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, -- timestamp when conversation was initiated
    last_message_at timestamp, -- timestamp of the last message in the conversation
    is_group_chat boolean NOT NULL DEFAULT false, -- indicates if it's a group chat or direct message
    group_name character varying(100), -- name of the group chat (if applicable)
    PRIMARY KEY (conversation_id)
)
CREATE TABLE social_media.conversation_participants (
    participant_id 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, -- unique identifier for the setting entry
    user_id character varying(64) NOT NULL UNIQUE, -- user the settings belong to (FK to users.user_id)
    theme character varying(20) DEFAULT 'light', -- UI theme ('light', 'dark')
    email_notifications_enabled boolean DEFAULT true, -- enable/disable email notifications
    push_notifications_enabled boolean DEFAULT true, -- enable/disable push notifications
    private_profile boolean DEFAULT false, -- is the user profile private
    updated_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, -- timestamp of last setting change
    PRIMARY KEY (setting_id)
)

[User] List each conversation_id and the number of unread messages (where read_at is null).

[Assistant] SELECT m.conversation_id, COUNT(*) AS unread_messages FROM social_media.messages m WHERE m.read_at IS NULL GROUP BY m.conversation_id;

[User] Now only include group chats and show the group_name.

[Assistant] SELECT c.conversation_id, c.group_name, COUNT(m.message_id) AS unread_messages 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.read_at IS NULL GROUP BY c.conversation_id, c.group_name;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE 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.reservations ( reservation_id character varying(64) NOT NULL, property_id character varying(64) NOT NULL, guest_id character varying(64) NOT NULL, room_id character varying(64), room_type_id character varying(64) NOT NULL, check_in_date date NOT NULL, check_out_date date NOT NULL, actual_check_in_ts timestamp with time zone, actual_check_out_ts timestamp with time zone, num_adults integer NOT NULL, num_children integer DEFAULT 0, status character varying(50) NOT NULL, booking_source character varying(100), rate_plan_id character varying(64), total_amount numeric(12, 2), amount_paid numeric(12, 2) DEFAULT 0.00, special_requests text, created_at timestamp with time zone NOT NULL DEFAULT current_timestamp, updated_at timestamp with time zone NOT NULL DEFAULT current_timestamp, PRIMARY KEY (reservation_id), FOREIGN KEY (property_id) REFERENCES hospitality_technology.properties(property_id), FOREIGN KEY (guest_id) REFERENCES hospitality_technology.guests(guest_id), FOREIGN KEY (room_id) REFERENCES hospitality_technology.rooms(room_id), FOREIGN KEY (room_type_id) REFERENCES hospitality_technology.room_types(room_type_id) )
CREATE TABLE hospitality_technology.staff ( staff_id text PRIMARY KEY, property_id text, first_name text, last_name text, position text, work_email text, work_phone text, hire_date date, termination_date date, is_active boolean, access_level int, manager_id text, created_at timestamp )
CREATE TABLE hospitality_technology.services ( service_id character varying(64) NOT NULL, property_id character varying(64) NOT NULL, service_name character varying(150) NOT NULL, description text, category character varying(100), price numeric(10, 2) NOT NULL, unit character varying(30), is_available boolean NOT NULL DEFAULT true, department character varying(100), PRIMARY KEY (service_id), FOREIGN KEY (property_id) REFERENCES hospitality_technology.properties(property_id) )
CREATE TABLE hospitality_technology.service_orders ( order_id text PRIMARY KEY, reservation_id text, guest_id text, service_id text, staff_id_ordered text, staff_id_delivered text, order_timestamp timestamp, delivery_timestamp timestamp, quantity int, unit_price numeric, total_price numeric, status text, notes text, bill_id text )

[User] List each property along with the total revenue generated from all delivered service orders, including the property name and total revenue.

[Assistant]
SELECT p.property_id, p.property_name, SUM(so.total_price) AS total_revenue
FROM hospitality_technology.properties p
JOIN hospitality_technology.services s ON s.property_id = p.property_id
JOIN hospitality_technology.service_orders so ON so.service_id = s.service_id
WHERE so.status = 'delivered'
GROUP BY p.property_id, p.property_name;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE government_services.service_locations ( location_id text PRIMARY KEY, agency_id text, location_name text, address text, city text, state text, postal_code text, latitude numeric, longitude numeric, operating_hours text, contact_phone text, is_accessible boolean )

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

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

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

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

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

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

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

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


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE 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] Can you show me all routes where the origin_location_id is the same as the destination_location_id? List their route_id, route_number, and type.

[Assistant]
SELECT route_id, route_number, type
FROM transportation.routes
WHERE origin_location_id = destination_location_id;

[User] I'd also like to know the distance_km and estimated_duration_minutes for these routes.

[Assistant]
SELECT route_id, route_number, type, distance_km, estimated_duration_minutes
FROM transportation.routes
WHERE origin_location_id = destination_location_id;

[User] Finally, only include those routes where estimated_duration_minutes is less than 30 and sort by distance_km descending.

[Assistant]
SELECT route_id, route_number, type, distance_km, estimated_duration_minutes
FROM transportation.routes
WHERE origin_location_id = destination_location_id
  AND estimated_duration_minutes < 30
ORDER BY distance_km DESC;