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.game_sessions ( session_id uuid, player_id uuid, game_id uuid, server_id uuid, start_time timestamp with time zone, end_time timestamp with time zone, duration_seconds integer, score integer, session_data jsonb )
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] For each player, show the total number of achievements they have unlocked and their total game session count.

[Assistant]
SELECT p.player_id, COUNT(pa.achievement_id) AS total_achievements_unlocked, COUNT(gs.session_id) AS total_sessions
FROM gaming_technology.player_achievements pa
FULL JOIN gaming_technology.game_sessions gs ON pa.player_id = gs.player_id
RIGHT JOIN (
    SELECT DISTINCT player_id FROM gaming_technology.player_achievements
    UNION
    SELECT DISTINCT player_id FROM gaming_technology.game_sessions
) p ON pa.player_id = p.player_id OR gs.player_id = p.player_id
GROUP BY p.player_id;

[User] Can you modify it to only include players who have unlocked at least 3 achievements and played at least 2 sessions?

[Assistant]
SELECT p.player_id, COUNT(pa.achievement_id) AS total_achievements_unlocked, COUNT(gs.session_id) AS total_sessions
FROM gaming_technology.player_achievements pa
FULL JOIN gaming_technology.game_sessions gs ON pa.player_id = gs.player_id
RIGHT JOIN (
    SELECT DISTINCT player_id FROM gaming_technology.player_achievements
    UNION
    SELECT DISTINCT player_id FROM gaming_technology.game_sessions
) p ON pa.player_id = p.player_id OR gs.player_id = p.player_id
GROUP BY p.player_id
HAVING COUNT(pa.achievement_id) >= 3 AND COUNT(gs.session_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 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
)

[User] List pairs of games that share the same publisher but belong to different genres, showing both titles and genres.

[Assistant]
SELECT g1.game_id AS game1_id,
       g1.title AS title1,
       g1.genre AS genre1,
       g2.game_id AS game2_id,
       g2.title AS title2,
       g2.genre AS genre2
FROM gaming_technology.games g1
JOIN gaming_technology.games g2
  ON g1.publisher_id = g2.publisher_id
  AND g1.game_id < g2.game_id
  AND g1.genre <> g2.genre;

[User] Exclude any pairs where the publisher_id is NULL.

[Assistant]
SELECT g1.game_id AS game1_id,
       g1.title AS title1,
       g1.genre AS genre1,
       g2.game_id AS game2_id,
       g2.title AS title2,
       g2.genre AS genre2
FROM gaming_technology.games g1
JOIN gaming_technology.games g2
  ON g1.publisher_id = g2.publisher_id
  AND g1.game_id < g2.game_id
  AND g1.genre <> g2.genre
WHERE g1.publisher_id IS NOT NULL;

[User] Further restrict to game pairs released within one year of each other.

[Assistant]
SELECT g1.game_id AS game1_id,
       g1.title AS title1,
       g1.release_date AS release1,
       g2.game_id AS game2_id,
       g2.title AS title2,
       g2.release_date AS release2
FROM gaming_technology.games g1
JOIN gaming_technology.games g2
  ON g1.publisher_id = g2.publisher_id
  AND g1.game_id < g2.game_id
  AND ABS(EXTRACT(YEAR FROM AGE(g1.release_date, g2.release_date))) <= 1
WHERE g1.publisher_id IS NOT NULL;

[User] Order the final result by publisher_id and then by the earliest release_date among each pair.

[Assistant]
SELECT g1.publisher_id,
       g1.game_id AS game1_id,
       g1.title AS title1,
       g1.release_date AS release1,
       g2.game_id AS game2_id,
       g2.title AS title2,
       g2.release_date AS release2
FROM gaming_technology.games g1
JOIN gaming_technology.games g2
  ON g1.publisher_id = g2.publisher_id
  AND g1.game_id < g2.game_id
  AND ABS(EXTRACT(YEAR FROM AGE(g1.release_date, g2.release_date))) <= 1
WHERE g1.publisher_id IS NOT NULL
ORDER BY g1.publisher_id,
         LEAST(g1.release_date, g2.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.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.developers ( developer_id.uuid, name.text, country.text, founded_year.integer, website.text, created_at.timestamptz )
CREATE TABLE gaming_technology.servers ( server_id uuid, game_id uuid, server_name text, region text, ip_address text, port integer, current_players integer, max_players integer, status text, last_heartbeat timestamp with time zone )
CREATE TABLE gaming_technology.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(), player_id uuid NOT NULL, item_id uuid NOT NULL, quantity integer NOT NULL DEFAULT 1, acquired_at timestamp with time zone NOT NULL DEFAULT CURRENT_TIMESTAMP, instance_data jsonb, PRIMARY KEY (inventory_id) )

[User] List all in-game items of type 'Consumable', showing for each item the item name, cost amount, and the total number of players who have that item in their inventory.

[Assistant]
SELECT i.item_name, i.cost_amount, COUNT(DISTINCT pi.player_id) AS player_count
FROM gaming_technology.in_game_items i
LEFT JOIN gaming_technology.player_inventory pi ON i.item_id = pi.item_id
WHERE i.item_type = 'Consumable'
GROUP BY i.item_id, i.item_name, i.cost_amount;

[User] Can you also show the total quantity held by all players for each item?

[Assistant]
SELECT i.item_name, i.cost_amount, COUNT(DISTINCT pi.player_id) AS player_count, COALESCE(SUM(pi.quantity), 0) AS total_quantity
FROM gaming_technology.in_game_items i
LEFT JOIN gaming_technology.player_inventory pi ON i.item_id = pi.item_id
WHERE i.item_type = 'Consumable'
GROUP BY i.item_id, i.item_name, i.cost_amount;

[User] Only include items where the total quantity is at least 10.

[Assistant]
SELECT i.item_name, i.cost_amount, COUNT(DISTINCT pi.player_id) AS player_count, COALESCE(SUM(pi.quantity), 0) AS total_quantity
FROM gaming_technology.in_game_items i
LEFT JOIN gaming_technology.player_inventory pi ON i.item_id = pi.item_id
WHERE i.item_type = 'Consumable'
GROUP BY i.item_id, i.item_name, i.cost_amount
HAVING COALESCE(SUM(pi.quantity), 0) >= 10;

[User] Sort the results by total_quantity in descending order.

[Assistant]
SELECT i.item_name, i.cost_amount, COUNT(DISTINCT pi.player_id) AS player_count, COALESCE(SUM(pi.quantity), 0) AS total_quantity
FROM gaming_technology.in_game_items i
LEFT JOIN gaming_technology.player_inventory pi ON i.item_id = pi.item_id
WHERE i.item_type = 'Consumable'
GROUP BY i.item_id, i.item_name, i.cost_amount
HAVING COALESCE(SUM(pi.quantity), 0) >= 10
ORDER BY total_quantity DESC;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE 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] List all game sessions that lasted longer than 30 minutes. Show the session_id, player_id, game_id, and duration_seconds.

[Assistant] SELECT session_id, player_id, game_id, duration_seconds FROM gaming_technology.game_sessions WHERE duration_seconds > 1800;

[User] Now, only include sessions that took place in the year 2023.

[Assistant] SELECT session_id, player_id, game_id, duration_seconds FROM gaming_technology.game_sessions WHERE duration_seconds > 1800 AND start_time >= '2023-01-01' AND start_time < '2024-01-01';

[User] Filter these sessions further to only show those with a score greater than 100.

[Assistant] SELECT session_id, player_id, game_id, duration_seconds FROM gaming_technology.game_sessions WHERE duration_seconds > 1800 AND start_time >= '2023-01-01' AND start_time < '2024-01-01' AND score > 100;

[User] Order the results by score in descending order and show only the top 5 entries.

[Assistant] SELECT session_id, player_id, game_id, duration_seconds FROM gaming_technology.game_sessions WHERE duration_seconds > 1800 AND start_time >= '2023-01-01' AND start_time < '2024-01-01' AND score > 100 ORDER BY score 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 timestamp with time zone )

[User] Show the number of achievements unlocked by each player per month. Display player_id, month (as YYYY-MM), and achievement_count.

[Assistant]
SELECT player_id,
       TO_CHAR(unlocked_at, 'YYYY-MM') AS year_month,
       COUNT(*) AS achievement_count
FROM gaming_technology.player_achievements
GROUP BY player_id, TO_CHAR(unlocked_at, 'YYYY-MM');

[User] Filter to months where players unlocked at least 5 achievements.

[Assistant]
SELECT player_id,
       TO_CHAR(unlocked_at, 'YYYY-MM') AS year_month,
       COUNT(*) AS achievement_count
FROM gaming_technology.player_achievements
GROUP BY player_id, TO_CHAR(unlocked_at, 'YYYY-MM')
HAVING COUNT(*) >= 5;

[User] Sort the results by year_month ascending and then by achievement_count descending.

[Assistant]
SELECT player_id,
       TO_CHAR(unlocked_at, 'YYYY-MM') AS year_month,
       COUNT(*) AS achievement_count
FROM gaming_technology.player_achievements
GROUP BY player_id, TO_CHAR(unlocked_at, 'YYYY-MM')
HAVING COUNT(*) >= 5
ORDER BY year_month ASC, achievement_count DESC;

[User] Limit the results to 10 rows.

[Assistant]
SELECT player_id,
       TO_CHAR(unlocked_at, 'YYYY-MM') AS year_month,
       COUNT(*) AS achievement_count
FROM gaming_technology.player_achievements
GROUP BY player_id, TO_CHAR(unlocked_at, 'YYYY-MM')
HAVING COUNT(*) >= 5
ORDER BY year_month ASC, achievement_count DESC
LIMIT 10;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE 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] Can you list for each player their most recent and second most recent achievements, showing columns player_id, recent_achievement_id, second_recent_achievement_id, and recent_unlocked_at?

[Assistant]
SELECT recent.player_id,
       recent.achievement_id AS recent_achievement_id,
       prev.achievement_id AS second_recent_achievement_id,
       recent.unlocked_at AS recent_unlocked_at
FROM (
  SELECT player_id, achievement_id, unlocked_at,
         ROW_NUMBER() OVER (PARTITION BY player_id ORDER BY unlocked_at DESC) AS rn
  FROM gaming_technology.player_achievements
) recent
JOIN (
  SELECT player_id, achievement_id,
         ROW_NUMBER() OVER (PARTITION BY player_id ORDER BY unlocked_at DESC) AS rn
  FROM gaming_technology.player_achievements
) prev
  ON recent.player_id = prev.player_id
WHERE recent.rn = 1 AND prev.rn = 2;

[User] Actually, please exclude any players who have less than two unlock records.

[Assistant]
WITH ranked AS (
  SELECT player_id, achievement_id, unlocked_at,
         ROW_NUMBER() OVER (PARTITION BY player_id ORDER BY unlocked_at DESC) AS rn,
         COUNT(*) OVER (PARTITION BY player_id) AS cnt
  FROM gaming_technology.player_achievements
)
SELECT recent.player_id,
       recent.achievement_id AS recent_achievement_id,
       prev.achievement_id AS second_recent_achievement_id,
       recent.unlocked_at AS recent_unlocked_at
FROM ranked recent
JOIN ranked prev
  ON recent.player_id = prev.player_id
WHERE recent.rn = 1
  AND prev.rn = 2
  AND recent.cnt >= 2;

[User] Also include the unlocked_at timestamp of the second most recent achievement.

[Assistant]
WITH ranked AS (
  SELECT player_id, achievement_id, unlocked_at,
         ROW_NUMBER() OVER (PARTITION BY player_id ORDER BY unlocked_at DESC) AS rn,
         COUNT(*) OVER (PARTITION BY player_id) AS cnt
  FROM gaming_technology.player_achievements
)
SELECT recent.player_id,
       recent.achievement_id AS recent_achievement_id,
       recent.unlocked_at AS recent_unlocked_at,
       prev.achievement_id AS second_recent_achievement_id,
       prev.unlocked_at AS second_recent_unlocked_at
FROM ranked recent
JOIN ranked prev
  ON recent.player_id = prev.player_id
WHERE recent.rn = 1
  AND prev.rn = 2
  AND recent.cnt >= 2;

[User] Finally, order the output by recent_unlocked_at in descending order.

[Assistant]
WITH ranked AS (
  SELECT player_id, achievement_id, unlocked_at,
         ROW_NUMBER() OVER (PARTITION BY player_id ORDER BY unlocked_at DESC) AS rn,
         COUNT(*) OVER (PARTITION BY player_id) AS cnt
  FROM gaming_technology.player_achievements
)
SELECT recent.player_id,
       recent.achievement_id AS recent_achievement_id,
       recent.unlocked_at AS recent_unlocked_at,
       prev.achievement_id AS second_recent_achievement_id,
       prev.unlocked_at AS second_recent_unlocked_at
FROM ranked recent
JOIN ranked prev
  ON recent.player_id = prev.player_id
WHERE recent.rn = 1 AND prev.rn = 2 AND recent.cnt >= 2
ORDER BY recent.unlocked_at DESC;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE gaming_technology.game_sessions ( session_id uuid PRIMARY KEY, player_id uuid, game_id uuid, server_id uuid, start_time timestamptz, end_time timestamptz, duration_seconds int, score int, session_data jsonb )

[User] For each server, what is the earliest and latest start time of its sessions?

[Assistant] SELECT server_id, MIN(start_time), MAX(start_time) FROM gaming_technology.game_sessions GROUP BY server_id;

[User] Only show servers where the difference between the earliest and latest session is more than 30 days.

[Assistant] SELECT server_id, MIN(start_time), MAX(start_time) FROM gaming_technology.game_sessions GROUP BY server_id HAVING MAX(start_time) - MIN(start_time) > INTERVAL '30 days';


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

[User] List all posts created by user 'U100' in March 2024.

[Assistant] SELECT post_id, user_id, content, created_at FROM social_media.posts WHERE user_id = 'U100' AND created_at >= '2024-03-01' AND created_at < '2024-04-01';

[User] Only show posts with `media_type` 'video'.

[Assistant] SELECT post_id, user_id, content, created_at, media_type FROM social_media.posts WHERE user_id = 'U100' AND created_at >= '2024-03-01' AND created_at < '2024-04-01' AND media_type = 'video';

[User] Order them by creation time descending and limit to the top 10.

[Assistant] SELECT post_id, user_id, content, created_at, media_type FROM social_media.posts WHERE user_id = 'U100' AND created_at >= '2024-03-01' AND created_at < '2024-04-01' AND media_type = 'video' ORDER BY created_at DESC LIMIT 10;

[User] Also, only include posts with `visibility` 'public'.

[Assistant] SELECT post_id, user_id, content, created_at, media_type, visibility FROM social_media.posts WHERE user_id = 'U100' AND created_at >= '2024-03-01' AND created_at < '2024-04-01' AND media_type = 'video' AND visibility = 'public' ORDER BY created_at DESC LIMIT 10;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
Index 'suppliers'. Mapping: { properties: { supplier_id: { type: 'keyword' }, supplier_name: { type: 'text', fields: { keyword: { type: 'keyword', ignore_above: 256 } } }, address: { type: 'text' }, country: { type: 'keyword' }, contact_person: { type: 'text', index: false }, contact_email: { type: 'keyword' }, quality_rating: { type: 'float' }, certified_date: { type: 'date' } } }. Document _id can be supplier_id.

[User] 특정 국가의 모든 공급업체 정보를 조회하고 싶습니다. 국가 이름, 공급업체 이름, 주소, 품질 등급을 포함해 주세요.

[Assistant]
GET suppliers/_search
{
  "query": {
    "term": {
      "country": "Korea"
    }
  },
  "_source": ["supplier_name", "address", "country", "quality_rating"]
}

[User] 품질 등급이 3.5 이상인 공급업체만 보고 싶습니다. 어떻게 수정해야 하나요?

[Assistant]
GET suppliers/_search
{
  "query": {
    "bool": {
      "must": [
        {
          "term": {
            "country": "Korea"
          }
        },
        {
          "range": {
            "quality_rating": {
              "gte": 3.5
            }
          }
        }
      ]
    }
  },
  "_source": ["supplier_name", "address", "country", "quality_rating"]
}

[User] 인증 날짜가 2020년 이후인 공급업체만 추가로 필터링하고 싶습니다.

[Assistant]
GET suppliers/_search
{
  "query": {
    "bool": {
      "must": [
        {
          "term": {
            "country": "Korea"
          }
        },
        {
          "range": {
            "quality_rating": {
              "gte": 3.5
            }
          }
        },
        {
          "range": {
            "certified_date": {
              "gte": "2020-01-01"
            }
          }
        }
      ]
    }
  },
  "_source": ["supplier_name", "address", "country", "quality_rating", "certified_date"]
}

[User] 결과를 품질 등급 기준으로 내림차순 정렬해 주세요.

[Assistant]
GET suppliers/_search
{
  "query": {
    "bool": {
      "must": [
        {
          "term": {
            "country": "Korea"
          }
        },
        {
          "range": {
            "quality_rating": {
              "gte": 3.5
            }
          }
        },
        {
          "range": {
            "certified_date": {
              "gte": "2020-01-01"
            }
          }
        }
      ]
    }
  },
  "_source": ["supplier_name", "address", "country", "quality_rating", "certified_date"],
  "sort": [
    {
      "quality_rating": {
        "order": "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 PRIMARY KEY, policy_id text, customer_id text, first_name text, last_name text, relationship text, percentage_share numeric, contact_info text, added_at timestamp )

[User] Show me all beneficiaries who are listed as 'Sibling' or 'Parent' on policies where their share is between 20 and 60 percent. Include beneficiary_id, policy_id, first_name, last_name, relationship, and percentage_share.

[Assistant]
SELECT beneficiary_id, policy_id, first_name, last_name, relationship, percentage_share
FROM insurance.policy_beneficiaries
WHERE relationship IN ('Sibling', 'Parent')
  AND percentage_share BETWEEN 20 AND 60;

[User] Actually, could you also include the contact_info for each beneficiary and only show beneficiaries who were added after January 1, 2024?

[Assistant]
SELECT beneficiary_id, policy_id, first_name, last_name, relationship, percentage_share, contact_info
FROM insurance.policy_beneficiaries
WHERE relationship IN ('Sibling', 'Parent')
  AND percentage_share BETWEEN 20 AND 60
  AND added_at > '2024-01-01';

[User] Only include beneficiaries where contact_info is not null and sort the results by added_at descending.

[Assistant]
SELECT beneficiary_id, policy_id, first_name, last_name, relationship, percentage_share, contact_info, added_at
FROM insurance.policy_beneficiaries
WHERE relationship IN ('Sibling', 'Parent')
  AND percentage_share BETWEEN 20 AND 60
  AND added_at > '2024-01-01'
  AND contact_info IS NOT NULL
ORDER BY added_at DESC;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
Node Label ':AircraftModel'. Properties: { model_id: String (Constraint: UNIQUE), model_name: String, manufacturer: String, passenger_capacity: Integer, max_range_km: Integer, engine_type: String, wingspan_m: Float, status: String, first_flight_date: Date }. Index on model_id.
Node Label ':Material'. Properties: { material_id: String (Constraint: UNIQUE), material_name: String, specification: String, description: String, density_kg_m3: Float, tensile_strength_mpa: Integer }. Index on material_id.
Node Label ':AssemblyLine'. Properties: { line_id: String (Constraint: UNIQUE), line_name: String, location_building: String, location_area: String, capacity_units_per_month: Integer, status: String }. Relationship: (:AssemblyLine)-[:BUILDS_MODEL]->(:AircraftModel {model_id}). Index on line_id.
Node Label ':AssemblyStep'. Properties: { step_id: String (Constraint: UNIQUE), step_number: Integer, step_name: String, description: String, standard_duration_hours: Float, required_skill_level: String, workstation: String }. Relationship: (:AssemblyLine {line_id})-[:HAS_STEP {sequence: <step_number>}]->(:AssemblyStep). Index on step_id.
Node Label ':AircraftBuild'. Properties: { build_id: String (Constraint: UNIQUE), serial_number: String (Constraint: UNIQUE), build_start_date: Datetime, estimated_completion_date: Date, actual_completion_date: Datetime, current_status: String, customer_order_id: String }. Relationships: (:AircraftBuild)-[:IS_MODEL]->(:AircraftModel {model_id}), (:AircraftBuild)-[:ASSEMBLED_ON]->(:AssemblyLine {line_id}). Index on build_id, serial_number, current_status.
Node Label ':Employee'. Properties: { employee_id: String (Constraint: UNIQUE), first_name: String, last_name: String, job_title: String, skill_certifications: String[], hire_date: Date, employment_status: String }. Relationships: (:Employee)-[:ASSIGNED_TO]->(:AssemblyLine {line_id}), (:Employee)-[:REPORTS_TO]->(:Employee {employee_id as supervisor_id}). Index on employee_id.
Node Label ':InventoryBatch'. Properties: { inventory_record_id: String (Constraint: UNIQUE), quantity: Integer, location_warehouse: String, location_bin: String, received_date: Datetime, expiry_date: Date, batch_number: String, last_updated: Datetime }. Relationship: (:InventoryBatch)-[:IS_INSTANCE_OF]->(:Component {component_id}). Index on inventory_record_id, component_id.

[User] Can you help me fetch the inventory details for components associated with a specific aircraft build, including the batch number, quantity, and warehouse location?

[Assistant]
MATCH (ab:AircraftBuild {build_id: 'specific_build_id'})-[:IS_MODEL]->(am:AircraftModel),
(ib:InventoryBatch)-[:IS_INSTANCE_OF]->(c:Component)
RETURN ib.inventory_record_id, ib.batch_number, ib.quantity, ib.location_warehouse

[User] Can you modify this to show only inventory batches received after a specific date, say June 1, 2023?

[Assistant]
MATCH (ab:AircraftBuild {build_id: 'specific_build_id'})-[:IS_MODEL]->(am:AircraftModel),
(ib:InventoryBatch)-[:IS_INSTANCE_OF]->(c:Component)
WHERE ib.received_date > datetime('2023-06-01')
RETURN ib.inventory_record_id, ib.batch_number, ib.quantity, ib.location_warehouse

[User] What if I also want to exclude batches with quantities less than 10?

[Assistant]
MATCH (ab:AircraftBuild {build_id: 'specific_build_id'})-[:IS_MODEL]->(am:AircraftModel),
(ib:InventoryBatch)-[:IS_INSTANCE_OF]->(c:Component)
WHERE ib.received_date > datetime('2023-06-01') AND ib.quantity >= 10
RETURN ib.inventory_record_id, ib.batch_number, ib.quantity, ib.location_warehouse


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE social_media.hashtags ( hashtag_id character varying(64) NOT NULL, tag_name character varying(100) NOT NULL UNIQUE, created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, PRIMARY KEY (hashtag_id) )

[User] List all hashtag names and their creation dates.

[Assistant] SELECT tag_name, created_at FROM social_media.hashtags;

[User] Please only include hashtags created in the year 2023.

[Assistant] SELECT tag_name, created_at FROM social_media.hashtags WHERE created_at >= '2023-01-01' AND created_at < '2024-01-01';


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE social_media.users ( user_id.text, username.text, email.text, password_hash.text, full_name.text, profile_picture_url.text, bio.text, location.text, created_at.timestamp, updated_at.timestamp, is_verified.boolean )

[User] How many users were registered in each month of 2024?

[Assistant]
SELECT date_trunc('month', created_at) AS month, COUNT(*) AS user_count
FROM social_media.users
WHERE created_at >= '2024-01-01'
  AND created_at < '2025-01-01'
GROUP BY month
ORDER BY month;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE social_media.hashtags ( hashtag_id.text, tag_name.text, created_at.timestamp )

[User] List all pairs of hashtags created within the same hour, including both hashtag IDs and their creation timestamps.

[Assistant] SELECT h1.hashtag_id AS hashtag1_id, h1.created_at AS created1, h2.hashtag_id AS hashtag2_id, h2.created_at AS created2 FROM hashtags h1 JOIN hashtags h2 ON date_trunc('hour', h1.created_at) = date_trunc('hour', h2.created_at) AND h1.hashtag_id < h2.hashtag_id;

[User] Actually, I also want to include the time difference in minutes between the two hashtags.

[Assistant] SELECT h1.hashtag_id AS hashtag1_id, h1.created_at AS created1, h2.hashtag_id AS hashtag2_id, h2.created_at AS created2, EXTRACT(EPOCH FROM (h2.created_at - h1.created_at)) / 60 AS diff_minutes FROM hashtags h1 JOIN hashtags h2 ON date_trunc('hour', h1.created_at) = date_trunc('hour', h2.created_at) AND h1.hashtag_id < h2.hashtag_id;

[User] Also, filter to only include pairs where both tag names start with the letter 'T'.

[Assistant] SELECT h1.hashtag_id AS hashtag1_id, h1.tag_name AS tag1, h2.hashtag_id AS hashtag2_id, h2.tag_name AS tag2, EXTRACT(EPOCH FROM (h2.created_at - h1.created_at)) / 60 AS diff_minutes FROM hashtags h1 JOIN hashtags h2 ON date_trunc('hour', h1.created_at) = date_trunc('hour', h2.created_at) AND h1.hashtag_id < h2.hashtag_id WHERE h1.tag_name LIKE 'T%' AND h2.tag_name LIKE 'T%';

[User] Finally, order the results by the earlier creation timestamp in descending order.

[Assistant] SELECT h1.hashtag_id AS hashtag1_id, h1.tag_name AS tag1, h2.hashtag_id AS hashtag2_id, h2.tag_name AS tag2, EXTRACT(EPOCH FROM (h2.created_at - h1.created_at)) / 60 AS diff_minutes FROM hashtags h1 JOIN hashtags h2 ON date_trunc('hour', h1.created_at) = date_trunc('hour', h2.created_at) AND h1.hashtag_id < h2.hashtag_id WHERE h1.tag_name LIKE 'T%' AND h2.tag_name LIKE 'T%' ORDER BY LEAST(h1.created_at, h2.created_at) DESC;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE healthcare.doctors ( doctor_id character varying(64) NOT NULL, first_name character varying(100) NOT NULL, last_name character varying(100) NOT NULL, specialty character varying(100) NOT NULL, license_number character varying(50) UNIQUE NOT NULL, phone_number character varying(20), email character varying(128) UNIQUE, hospital_affiliation_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 (doctor_id) )
CREATE TABLE healthcare.appointments ( appointment_id character varying(64) NOT NULL, patient_id character varying(64) NOT NULL, doctor_id character varying(64) NOT NULL, appointment_time timestamp with time zone NOT NULL, duration_minutes integer NOT NULL, reason text, status character varying(32) NOT NULL, location_id character varying(64), notes text, created_at timestamp with time zone NOT NULL DEFAULT current_timestamp, PRIMARY KEY (appointment_id) )
CREATE TABLE healthcare.medical_records ( record_id character varying(64) NOT NULL, patient_id character varying(64) NOT NULL, appointment_id character varying(64) UNIQUE, doctor_id character varying(64) NOT NULL, record_date timestamp with time zone NOT NULL, chief_complaint text, present_illness_history text, past_medical_history text, physical_examination_notes text, assessment text, treatment_plan text, vitals jsonb, created_at timestamp with time zone NOT NULL DEFAULT current_timestamp, PRIMARY KEY (record_id) )
CREATE TABLE healthcare.diagnoses ( diagnosis_id character varying(64) NOT NULL, 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.insurance_plans ( plan_id character varying(64) NOT NULL, plan_name character varying(200) NOT NULL, insurance_provider character varying(100) NOT NULL, plan_type character varying(50), contact_phone character varying(20), website character varying(255), PRIMARY KEY (plan_id) )
CREATE TABLE healthcare.patient_insurance ( patient_insurance_id character varying(64) NOT NULL, patient_id character varying(64) NOT NULL, plan_id character varying(64) NOT NULL, policy_number character varying(100) NOT NULL, group_number character varying(100), subscriber_name character varying(200), effective_date date NOT NULL, expiration_date date, is_primary boolean NOT NULL DEFAULT true, PRIMARY KEY (patient_insurance_id), UNIQUE (patient_id, plan_id, policy_number) )

[User] Can you show me the count of new doctors added each month in 2023? Return the month and number of doctors.

[Assistant]
SELECT DATE_TRUNC('month', created_at) AS month, COUNT(*) AS doctor_count
FROM healthcare.doctors
WHERE created_at >= '2023-01-01' AND created_at < '2024-01-01'
GROUP BY DATE_TRUNC('month', created_at);

[User] Actually, include the month as the first day of the month and order the results by month in descending order.

[Assistant]
SELECT DATE_TRUNC('month', created_at)::date AS month_start, COUNT(*) AS doctor_count
FROM healthcare.doctors
WHERE created_at >= '2023-01-01' AND created_at < '2024-01-01'
GROUP BY DATE_TRUNC('month', created_at)
ORDER BY month_start 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.patients ( patient_id text, first_name text, last_name text, date_of_birth date, gender text, address text, phone_number text, email text, emergency_contact_name text, emergency_contact_phone text, created_at timestamp, updated_at timestamp )
CREATE TABLE healthcare.doctors ( doctor_id text, 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.medical_records ( record_id character varying(64) NOT NULL, patient_id character varying(64) NOT NULL, appointment_id character varying(64) UNIQUE, doctor_id character varying(64) NOT NULL, record_date timestamp with time zone NOT NULL, chief_complaint text, present_illness_history text, past_medical_history text, physical_examination_notes text, assessment text, treatment_plan text, vitals jsonb, created_at timestamp with time zone NOT NULL DEFAULT current_timestamp, PRIMARY KEY (record_id) )
CREATE TABLE healthcare.diagnoses ( diagnosis_id text PRIMARY KEY, record_id text, patient_id text, doctor_id text, diagnosis_code text, code_type text, description text, diagnosis_date date, status text, is_chronic boolean )
CREATE TABLE healthcare.prescriptions ( prescription_id character varying(64) NOT NULL, record_id character varying(64) NOT NULL, patient_id character varying(64) NOT NULL, doctor_id character varying(64) NOT NULL, medication_id character varying(64) NOT NULL, dosage character varying(100) NOT NULL, frequency character varying(100) NOT NULL, route character varying(50), start_date date NOT NULL, end_date date, quantity_dispensed numeric(10,2), refills_allowed integer NOT NULL DEFAULT 0, prescription_date timestamp with time zone NOT NULL DEFAULT current_timestamp, PRIMARY KEY (prescription_id) )
CREATE TABLE healthcare.insurance_plans ( plan_id character varying(64) NOT NULL, plan_name character varying(200) NOT NULL, insurance_provider character varying(100) NOT NULL, plan_type character varying(50), contact_phone character varying(20), website character varying(255), PRIMARY KEY (plan_id) )
CREATE TABLE healthcare.patient_insurance (
    patient_insurance_id character varying(64) NOT NULL, -- unique identifier for this patient-plan link
    patient_id character varying(64) NOT NULL, -- FK to patients table
    plan_id character varying(64) NOT NULL, -- FK to insurance_plans table
    policy_number character varying(100) NOT NULL, -- patient's policy number
    group_number character varying(100), -- group number, if applicable
    subscriber_name character varying(200), -- name of the primary policy holder
    effective_date date NOT NULL, -- date the coverage begins
    expiration_date date, -- date the coverage ends (if known)
    is_primary boolean NOT NULL DEFAULT true, -- indicates if this is the primary insurance
    PRIMARY KEY (patient_insurance_id),
    UNIQUE (patient_id, plan_id, policy_number) -- ensure a patient doesn't have the same policy twice
)

[User] What is the average number of refills allowed across all prescriptions?

[Assistant] SELECT AVG(refills_allowed) FROM healthcare.prescriptions;


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.medications (
    medication_id character varying(64) NOT NULL, -- unique identifier for the medication type
    medication_name character varying(255) NOT NULL, -- common or brand name
    generic_name character varying(255), -- generic chemical name
    manufacturer character varying(100), -- drug manufacturer
    ndc_code character varying(20) UNIQUE, -- National Drug Code (optional but useful)
    description text, -- description of the medication
    PRIMARY KEY (medication_id)
)

[User] List the medication_id, medication_name, and description for all medications whose generic_name starts with 'A'.

[Assistant]
SELECT medication_id, medication_name, description
FROM healthcare.medications
WHERE generic_name LIKE 'A%';


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE healthcare.patients ( patient_id text, first_name text, last_name text, date_of_birth date, gender text, address text, phone_number text, email text, emergency_contact_name text, emergency_contact_phone text, created_at timestamp, updated_at timestamp )
CREATE TABLE healthcare.doctors ( doctor_id text, 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.appointments (
    appointment_id character varying(64) NOT NULL, -- unique identifier for the appointment
    patient_id character varying(64) NOT NULL, -- FK to patients table
    doctor_id character varying(64) NOT NULL, -- FK to doctors table
    appointment_time timestamp with time zone NOT NULL, -- date and time of the appointment
    duration_minutes integer NOT NULL, -- expected duration in minutes
    reason text, -- reason for the visit
    status character varying(32) NOT NULL, -- e.g., Scheduled, Completed, Cancelled, No-show
    location_id character varying(64), -- FK to a potential locations/clinics table
    notes text, -- notes related to scheduling
    created_at timestamp with time zone NOT NULL DEFAULT current_timestamp,
    PRIMARY KEY (appointment_id)
)
CREATE TABLE healthcare.medical_records ( record_id text PRIMARY KEY, patient_id text, appointment_id text, doctor_id text, record_date timestamp, chief_complaint text, present_illness_history text, past_medical_history text, physical_examination_notes text, assessment text, treatment_plan text, vitals text, created_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.medications (
    medication_id character varying(64) NOT NULL, -- unique identifier for the medication type
    medication_name character varying(255) NOT NULL, -- common or brand name
    generic_name character varying(255), -- generic chemical name
    manufacturer character varying(100), -- drug manufacturer
    ndc_code character varying(20) UNIQUE, -- National Drug Code (optional but useful)
    description text, -- description of the medication
    PRIMARY KEY (medication_id)
)
CREATE TABLE healthcare.prescriptions ( prescription_id text, record_id text, patient_id text, doctor_id text, medication_id text, dosage text, frequency text, route text, start_date date, end_date date, quantity_dispensed numeric, refills_allowed integer, prescription_date timestamp )
CREATE TABLE healthcare.insurance_plans ( plan_id.text, plan_name.text, insurance_provider.text, plan_type.text, contact_phone.text, website.text )

[User] Show me a list of all patient names along with the full names of their doctors for appointments scheduled in February 2024.

[Assistant]
SELECT p.first_name AS patient_first_name, p.last_name AS patient_last_name, d.first_name AS doctor_first_name, d.last_name AS doctor_last_name
FROM healthcare.appointments a
JOIN healthcare.patients p ON a.patient_id = p.patient_id
JOIN healthcare.doctors d ON a.doctor_id = d.doctor_id
WHERE a.status = 'Scheduled' AND DATE_TRUNC('month', a.appointment_time) = DATE '2024-02-01';

[User] Actually, can you also include the appointment time for each result?

[Assistant]
SELECT p.first_name AS patient_first_name, p.last_name AS patient_last_name, d.first_name AS doctor_first_name, d.last_name AS doctor_last_name, a.appointment_time
FROM healthcare.appointments a
JOIN healthcare.patients p ON a.patient_id = p.patient_id
JOIN healthcare.doctors d ON a.doctor_id = d.doctor_id
WHERE a.status = 'Scheduled' AND DATE_TRUNC('month', a.appointment_time) = DATE '2024-02-01';

[User] I got an error: column 'appointment_time' does not exist. Can you check and fix the query?

[Assistant]
SELECT p.first_name AS patient_first_name, p.last_name AS patient_last_name, d.first_name AS doctor_first_name, d.last_name AS doctor_last_name, a.appointment_time
FROM healthcare.appointments a
JOIN healthcare.patients p ON a.patient_id = p.patient_id
JOIN healthcare.doctors d ON a.doctor_id = d.doctor_id
WHERE a.status = 'Scheduled' AND DATE_TRUNC('month', a.appointment_time) = DATE '2024-02-01';


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE healthcare.patients (
    patient_id character varying(64) NOT NULL,  -- unique identifier for the patient
    first_name character varying(100) NOT NULL, -- patient's first name
    last_name character varying(100) NOT NULL, -- patient's last name
    date_of_birth date NOT NULL, -- patient's date of birth
    gender character varying(10), -- patient's gender (e.g., Male, Female, Other)
    address text, -- patient's home address
    phone_number character varying(20), -- patient's phone number
    email character varying(128) UNIQUE, -- patient's email address
    emergency_contact_name character varying(200), -- name of emergency contact
    emergency_contact_phone character varying(20), -- phone number of emergency contact
    created_at timestamp with time zone NOT NULL DEFAULT current_timestamp, -- record creation time
    updated_at timestamp with time zone NOT NULL DEFAULT current_timestamp, -- record last update time
    PRIMARY KEY (patient_id)
)
CREATE TABLE healthcare.appointments (
    appointment_id character varying(64) NOT NULL, -- unique identifier for the appointment
    patient_id character varying(64) NOT NULL, -- FK to patients table
    doctor_id character varying(64) NOT NULL, -- FK to doctors table
    appointment_time timestamp with time zone NOT NULL, -- date and time of the appointment
    duration_minutes integer NOT NULL, -- expected duration in minutes
    reason text, -- reason for the visit
    status character varying(32) NOT NULL, -- e.g., Scheduled, Completed, Cancelled, No-show
    location_id character varying(64), -- FK to a potential locations/clinics table
    notes text, -- notes related to scheduling
    created_at timestamp with time zone NOT NULL DEFAULT current_timestamp,
    PRIMARY KEY (appointment_id)
)
CREATE TABLE healthcare.medical_records (
    record_id character varying(64) NOT NULL,  -- unique identifier for the medical record entry
    patient_id character varying(64) NOT NULL, -- FK to patients table
    appointment_id character varying(64) UNIQUE, -- FK to appointments table (can be null if record not tied to specific appt)
    doctor_id character varying(64) NOT NULL, -- FK to doctors table (doctor creating the record)
    record_date timestamp with time zone NOT NULL, -- date the record/observation was made
    chief_complaint text, -- patient's primary reason for visit
    present_illness_history text, -- detailed history of the current issue
    past_medical_history text, -- relevant past conditions/surgeries
    physical_examination_notes text, -- findings from the physical exam
    assessment text, -- doctor's assessment/diagnosis summary
    treatment_plan text, -- planned course of action
    vitals jsonb, -- store vitals like BP, HR, Temp as structured JSON
    created_at timestamp with time zone NOT NULL DEFAULT current_timestamp,
    PRIMARY KEY (record_id)
)

[User] List appointment IDs, patient first and last names, and their chief complaint for appointments that have an associated medical record.

[Assistant]
SELECT a.appointment_id, p.first_name, p.last_name, mr.chief_complaint
FROM healthcare.appointments a
JOIN healthcare.medical_records mr
  ON a.appointment_id = mr.appointment_id
JOIN healthcare.patients p
  ON a.patient_id = p.patient_id;

[User] Also include the appointment_time and only include records from the past 30 days.

[Assistant]
SELECT a.appointment_id, p.first_name, p.last_name, mr.chief_complaint, a.appointment_time
FROM healthcare.appointments a
JOIN healthcare.medical_records mr
  ON a.appointment_id = mr.appointment_id
JOIN healthcare.patients p
  ON a.patient_id = p.patient_id
WHERE mr.record_date >= NOW() - INTERVAL '30 days';


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

[User] Show me a list of all appointments and the number of prescriptions that were issued on the same day for each appointment.

[Assistant]
SELECT a.appointment_id, a.appointment_time::date AS appointment_date,
       COUNT(pr.prescription_id) AS prescriptions_count
FROM healthcare.appointments a
LEFT JOIN healthcare.medical_records mr ON mr.appointment_id = a.appointment_id
LEFT JOIN healthcare.prescriptions pr ON pr.record_id = mr.record_id
GROUP BY a.appointment_id, a.appointment_time::date;

[User] Only include appointments where at least one prescription was made that day, and show the full names of the patient and doctor for each appointment.

[Assistant]
SELECT a.appointment_id, a.appointment_time::date AS appointment_date,
       p.first_name || ' ' || p.last_name AS patient_full_name,
       d.first_name || ' ' || d.last_name AS doctor_full_name,
       COUNT(pr.prescription_id) AS prescriptions_count
FROM healthcare.appointments a
JOIN healthcare.patients p ON a.patient_id = p.patient_id
JOIN healthcare.doctors d ON a.doctor_id = d.doctor_id
LEFT JOIN healthcare.medical_records mr ON mr.appointment_id = a.appointment_id
LEFT JOIN healthcare.prescriptions pr ON pr.record_id = mr.record_id
GROUP BY a.appointment_id, a.appointment_time::date, p.first_name, p.last_name, d.first_name, d.last_name
HAVING COUNT(pr.prescription_id) > 0;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE healthcare.doctors (
    doctor_id character varying(64) NOT NULL,  -- unique identifier for the doctor
    first_name character varying(100) NOT NULL, -- doctor's first name
    last_name character varying(100) NOT NULL, -- doctor's last name
    specialty character varying(100) NOT NULL, -- doctor's medical specialty
    license_number character varying(50) UNIQUE NOT NULL, -- doctor's medical license number
    phone_number character varying(20), -- doctor's contact phone
    email character varying(128) UNIQUE, -- doctor's contact email
    hospital_affiliation_id character varying(64), -- FK to hospitals table (optional)
    created_at timestamp with time zone NOT NULL DEFAULT current_timestamp,
    updated_at timestamp with time zone NOT NULL DEFAULT current_timestamp,
    PRIMARY KEY (doctor_id)
)
CREATE TABLE healthcare.appointments (
    appointment_id character varying(64) NOT NULL, -- unique identifier for the appointment
    patient_id character varying(64) NOT NULL, -- FK to patients table
    doctor_id character varying(64) NOT NULL, -- FK to doctors table
    appointment_time timestamp with time zone NOT NULL, -- date and time of the appointment
    duration_minutes integer NOT NULL, -- expected duration in minutes
    reason text, -- reason for the visit
    status character varying(32) NOT NULL, -- e.g., Scheduled, Completed, Cancelled, No-show
    location_id character varying(64), -- FK to a potential locations/clinics table
    notes text, -- notes related to scheduling
    created_at timestamp with time zone NOT NULL DEFAULT current_timestamp,
    PRIMARY KEY (appointment_id)
)
CREATE TABLE healthcare.diagnoses (
    diagnosis_id character varying(64) NOT NULL, -- unique identifier for the diagnosis entry
    record_id character varying(64) NOT NULL, -- FK linking to the specific medical record entry
    patient_id character varying(64) NOT NULL, -- FK to patients table
    doctor_id character varying(64) NOT NULL, -- FK to doctors table (diagnosing doctor)
    diagnosis_code character varying(20) NOT NULL, -- standard code (e.g., ICD-10)
    code_type character varying(10) NOT NULL DEFAULT 'ICD-10', -- type of code used
    description text, -- textual description of the diagnosis
    diagnosis_date date NOT NULL, -- date the diagnosis was made
    status character varying(32) NOT NULL, -- e.g., Active, Resolved, Ruled Out
    is_chronic boolean DEFAULT false, -- flag for chronic conditions
    PRIMARY KEY (diagnosis_id)
)
CREATE TABLE healthcare.medications (
    medication_id character varying(64) NOT NULL, -- unique identifier for the medication type
    medication_name character varying(255) NOT NULL, -- common or brand name
    generic_name character varying(255), -- generic chemical name
    manufacturer character varying(100), -- drug manufacturer
    ndc_code character varying(20) UNIQUE, -- National Drug Code (optional but useful)
    description text, -- description of the medication
    PRIMARY KEY (medication_id)
)

[User] List the description and diagnosis date for all diagnoses that are marked as chronic and were made in the year 2023.

[Assistant] SELECT description, diagnosis_date FROM healthcare.diagnoses WHERE is_chronic = true AND diagnosis_date BETWEEN '2023-01-01' AND '2023-12-31';

[User] Also include the patient ID and order the results by diagnosis date ascending.

[Assistant] SELECT patient_id, description, diagnosis_date FROM healthcare.diagnoses WHERE is_chronic = true AND diagnosis_date BETWEEN '2023-01-01' AND '2023-12-31' ORDER BY diagnosis_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 healthcare.patients (
    patient_id character varying(64) NOT NULL,  -- unique identifier for the patient
    first_name character varying(100) NOT NULL, -- patient's first name
    last_name character varying(100) NOT NULL, -- patient's last name
    date_of_birth date NOT NULL, -- patient's date of birth
    gender character varying(10), -- patient's gender (e.g., Male, Female, Other)
    address text, -- patient's home address
    phone_number character varying(20), -- patient's phone number
    email character varying(128) UNIQUE, -- patient's email address
    emergency_contact_name character varying(200), -- name of emergency contact
    emergency_contact_phone character varying(20), -- phone number of emergency contact
    created_at timestamp with time zone NOT NULL DEFAULT current_timestamp, -- record creation time
    updated_at timestamp with time zone NOT NULL DEFAULT current_timestamp, -- record last update time
    PRIMARY KEY (patient_id)
)
CREATE TABLE healthcare.doctors ( doctor_id 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.appointments (
    appointment_id character varying(64) NOT NULL, -- unique identifier for the appointment
    patient_id character varying(64) NOT NULL, -- FK to patients table
    doctor_id character varying(64) NOT NULL, -- FK to doctors table
    appointment_time timestamp with time zone NOT NULL, -- date and time of the appointment
    duration_minutes integer NOT NULL, -- expected duration in minutes
    reason text, -- reason for the visit
    status character varying(32) NOT NULL, -- e.g., Scheduled, Completed, Cancelled, No-show
    location_id character varying(64), -- FK to a potential locations/clinics table
    notes text, -- notes related to scheduling
    created_at timestamp with time zone NOT NULL DEFAULT current_timestamp,
    PRIMARY KEY (appointment_id)
)
CREATE TABLE healthcare.medical_records ( record_id.text, patient_id.text, appointment_id.text, doctor_id.text, record_date.timestamp, chief_complaint.text, present_illness_history.text, past_medical_history.text, physical_examination_notes.text, assessment.text, treatment_plan.text, vitals.json, created_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.medications ( medication_id text PRIMARY KEY, medication_name text, generic_name text, manufacturer text, ndc_code text, description text )
CREATE TABLE healthcare.prescriptions ( prescription_id text, record_id text, patient_id text, doctor_id text, medication_id text, dosage text, frequency text, route text, start_date date, end_date date, quantity_dispensed numeric, refills_allowed integer, prescription_date timestamp )
CREATE TABLE healthcare.patient_insurance (
    patient_insurance_id character varying(64) NOT NULL, -- 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 all prescriptions with medication details. Return prescription_id, patient full name, medication_name, and prescription_date.

[Assistant]
SELECT pr.prescription_id,
       p.first_name || ' ' || p.last_name AS patient_name,
       m.medication_name,
       pr.prescription_date
FROM healthcare.prescriptions pr
JOIN healthcare.patients p ON pr.patient_id = p.patient_id
JOIN healthcare.medications m ON pr.medication_id = m.medication_id;

[User] Filter to only include prescriptions where the quantity_dispensed is greater than 30.

[Assistant]
SELECT pr.prescription_id,
       p.first_name || ' ' || p.last_name AS patient_name,
       m.medication_name,
       pr.prescription_date
FROM healthcare.prescriptions pr
JOIN healthcare.patients p ON pr.patient_id = p.patient_id
JOIN healthcare.medications m ON pr.medication_id = m.medication_id
WHERE pr.quantity_dispensed > 30;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE healthcare.patients ( patient_id character varying(64) NOT NULL, first_name character varying(100) NOT NULL, last_name character varying(100) NOT NULL, date_of_birth date NOT NULL, gender character varying(10), address text, phone_number character varying(20), email character varying(128) UNIQUE, emergency_contact_name character varying(200), emergency_contact_phone character varying(20), created_at timestamp with time zone NOT NULL DEFAULT current_timestamp, updated_at timestamp with time zone NOT NULL DEFAULT current_timestamp, PRIMARY KEY (patient_id) )
CREATE TABLE healthcare.appointments ( appointment_id text, patient_id text, doctor_id text, appointment_time timestamp, duration_minutes integer, reason text, status text, location_id text, notes text, created_at timestamp )
CREATE TABLE healthcare.medical_records ( record_id character varying(64) NOT NULL, patient_id character varying(64) NOT NULL, appointment_id character varying(64) UNIQUE, doctor_id character varying(64) NOT NULL, record_date timestamp with time zone NOT NULL, chief_complaint text, present_illness_history text, past_medical_history text, physical_examination_notes text, assessment text, treatment_plan text, vitals jsonb, created_at timestamp with time zone NOT NULL DEFAULT current_timestamp, PRIMARY KEY (record_id) )
CREATE TABLE healthcare.diagnoses ( diagnosis_id text PRIMARY KEY, record_id text, patient_id text, doctor_id text, diagnosis_code text, code_type text, description text, diagnosis_date date, status text, is_chronic boolean )
CREATE TABLE healthcare.medications ( medication_id text, medication_name text, generic_name text, manufacturer text, ndc_code text, description text )
CREATE TABLE healthcare.prescriptions ( prescription_id.text, record_id.text, patient_id.text, doctor_id.text, medication_id.text, dosage.text, frequency.text, route.text, start_date.date, end_date.date, quantity_dispensed.numeric, refills_allowed.integer, prescription_date.timestamp )
CREATE TABLE healthcare.insurance_plans ( plan_id.text, plan_name.text, insurance_provider.text, plan_type.text, contact_phone.text, website.text )
CREATE TABLE healthcare.patient_insurance ( patient_insurance_id character varying(64) NOT NULL, patient_id character varying(64) NOT NULL, plan_id character varying(64) NOT NULL, policy_number character varying(100) NOT NULL, group_number character varying(100), subscriber_name character varying(200), effective_date date NOT NULL, expiration_date date, is_primary boolean NOT NULL DEFAULT true, PRIMARY KEY (patient_insurance_id), UNIQUE (patient_id, plan_id, policy_number) )

[User] List each patient's first and last name along with the insurance plan name they are enrolled in, including only primary policies. Return patient_id, first_name, last_name, and plan_name.

[Assistant]
SELECT p.patient_id,
       p.first_name,
       p.last_name,
       ip.plan_name
FROM healthcare.patients AS p
JOIN healthcare.patient_insurance AS pi
  ON p.patient_id = pi.patient_id AND pi.is_primary = true
JOIN healthcare.insurance_plans AS ip ON pi.plan_id = ip.plan_id;

[User] Now limit to plans with plan_type 'EPO' and sort by patient last name ascending.

[Assistant]
SELECT p.patient_id,
       p.first_name,
       p.last_name,
       ip.plan_name
FROM healthcare.patients AS p
JOIN healthcare.patient_insurance AS pi
  ON p.patient_id = pi.patient_id AND pi.is_primary = true
JOIN healthcare.insurance_plans AS ip ON pi.plan_id = ip.plan_id
WHERE ip.plan_type = 'EPO'
ORDER BY p.last_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 healthcare.doctors ( doctor_id character varying(64) NOT NULL, first_name character varying(100) NOT NULL, last_name character varying(100) NOT NULL, specialty character varying(100) NOT NULL, license_number character varying(50) UNIQUE NOT NULL, phone_number character varying(20), email character varying(128) UNIQUE, hospital_affiliation_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 (doctor_id) )
CREATE TABLE healthcare.medical_records ( record_id character varying(64) NOT NULL, patient_id character varying(64) NOT NULL, appointment_id character varying(64) UNIQUE, doctor_id character varying(64) NOT NULL, record_date timestamp with time zone NOT NULL, chief_complaint text, present_illness_history text, past_medical_history text, physical_examination_notes text, assessment text, treatment_plan text, vitals jsonb, created_at timestamp with time zone NOT NULL DEFAULT current_timestamp, PRIMARY KEY (record_id) )
CREATE TABLE healthcare.diagnoses ( diagnosis_id text PRIMARY KEY, record_id text, patient_id text, doctor_id text, diagnosis_code text, code_type text, description text, diagnosis_date date, status text, is_chronic boolean )
CREATE TABLE healthcare.medications ( medication_id text, medication_name text, generic_name text, manufacturer text, ndc_code text, description text )
CREATE TABLE healthcare.insurance_plans ( plan_id.text, plan_name.text, insurance_provider.text, plan_type.text, contact_phone.text, website.text )

[User] Show a list of diagnoses along with the chief complaint noted in the corresponding medical record. Display diagnosis description, diagnosis date, and the chief complaint.

[Assistant] SELECT T1.description, T1.diagnosis_date, T2.chief_complaint FROM healthcare.diagnoses AS T1 JOIN healthcare.medical_records AS T2 ON T1.record_id = T2.record_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.diagnoses ( diagnosis_id character varying(64) NOT NULL, record_id character varying(64) NOT NULL, patient_id character varying(64) NOT NULL, doctor_id character varying(64) NOT NULL, diagnosis_code character varying(20) NOT NULL, code_type character varying(10) NOT NULL DEFAULT 'ICD-10', description text, diagnosis_date date NOT NULL, status character varying(32) NOT NULL, is_chronic boolean DEFAULT false, PRIMARY KEY (diagnosis_id) )
CREATE TABLE healthcare.prescriptions ( prescription_id character varying(64) NOT NULL, record_id character varying(64) NOT NULL, patient_id character varying(64) NOT NULL, doctor_id character varying(64) NOT NULL, medication_id character varying(64) NOT NULL, dosage character varying(100) NOT NULL, frequency character varying(100) NOT NULL, route character varying(50), start_date date NOT NULL, end_date date, quantity_dispensed numeric(10,2), refills_allowed integer NOT NULL DEFAULT 0, prescription_date timestamp with time zone NOT NULL DEFAULT current_timestamp, PRIMARY KEY (prescription_id) )
CREATE TABLE healthcare.patient_insurance ( patient_insurance_id character varying(64) NOT NULL, patient_id character varying(64) NOT NULL, plan_id character varying(64) NOT NULL, policy_number character varying(100) NOT NULL, group_number character varying(100), subscriber_name character varying(200), effective_date date NOT NULL, expiration_date date, is_primary boolean NOT NULL DEFAULT true, PRIMARY KEY (patient_insurance_id), UNIQUE (patient_id, plan_id, policy_number) )

[User] Show each patient's policy number, the associated insurance plan ID, and any medications they have been prescribed, including the medication ID and prescription date.

[Assistant]
SELECT pi.patient_id, pi.policy_number, pi.plan_id, pr.medication_id, pr.prescription_date
FROM healthcare.patient_insurance pi
JOIN healthcare.prescriptions pr ON pi.patient_id = pr.patient_id;

[User] Only include prescriptions that were made after the insurance policy's effective date.

[Assistant]
SELECT pi.patient_id, pi.policy_number, pi.plan_id, pr.medication_id, pr.prescription_date
FROM healthcare.patient_insurance pi
JOIN healthcare.prescriptions pr ON pi.patient_id = pr.patient_id
WHERE pr.prescription_date >= pi.effective_date;

[User] Add the expiration date of the insurance policy and only show records where the prescription was made before the policy expired.

[Assistant]
SELECT pi.patient_id, pi.policy_number, pi.plan_id, pi.expiration_date, pr.medication_id, pr.prescription_date
FROM healthcare.patient_insurance pi
JOIN healthcare.prescriptions pr ON pi.patient_id = pr.patient_id
WHERE pr.prescription_date >= pi.effective_date
  AND (pi.expiration_date IS NULL OR pr.prescription_date < pi.expiration_date);


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] Show me all primary insurance policies along with their policy numbers and effective dates for patient with ID 'patient_555'.

[Assistant] SELECT patient_insurance_id, policy_number, effective_date FROM healthcare.patient_insurance WHERE patient_id = 'patient_555' AND is_primary = TRUE;

[User] Can you also show the group number for each policy?

[Assistant] SELECT patient_insurance_id, policy_number, effective_date, group_number FROM healthcare.patient_insurance WHERE patient_id = 'patient_555' AND is_primary = TRUE;

[User] I only want to see those policies that are still active.

[Assistant] SELECT patient_insurance_id, policy_number, effective_date, group_number FROM healthcare.patient_insurance WHERE patient_id = 'patient_555' AND is_primary = TRUE AND expiration_date > CURRENT_DATE;

[User] Actually, can you order the results by expiration_date, with the soonest expiration first?

[Assistant] SELECT patient_insurance_id, policy_number, effective_date, group_number FROM healthcare.patient_insurance WHERE patient_id = 'patient_555' AND is_primary = TRUE AND expiration_date > CURRENT_DATE ORDER BY expiration_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 healthcare.diagnoses ( diagnosis_id.text, record_id.text, patient_id.text, doctor_id.text, diagnosis_code.text, code_type.text, description.text, diagnosis_date.date, status.text, is_chronic.boolean )

[User] Can you show me the total number of diagnosis records for each doctor, along with the doctor's ID? Please include only those diagnoses marked as 'chronic'.

[Assistant] SELECT doctor_id, COUNT(*) AS total_chronic_diagnoses FROM healthcare.diagnoses WHERE is_chronic = TRUE GROUP BY doctor_id;

[User] Now, can you also include the average number of chronic diagnoses per patient for each doctor in the results?

[Assistant] SELECT doctor_id, COUNT(*) AS total_chronic_diagnoses, COUNT(*)::FLOAT / COUNT(DISTINCT patient_id) AS avg_chronic_per_patient FROM healthcare.diagnoses WHERE is_chronic = TRUE GROUP BY doctor_id;

[User] Please filter the results to only include doctors with at least 5 chronic diagnoses.

[Assistant] SELECT doctor_id, COUNT(*) AS total_chronic_diagnoses, COUNT(*)::FLOAT / COUNT(DISTINCT patient_id) AS avg_chronic_per_patient FROM healthcare.diagnoses WHERE is_chronic = TRUE GROUP BY doctor_id HAVING COUNT(*) >= 5;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE healthcare.medical_records ( record_id text, patient_id text, appointment_id text, doctor_id text, record_date timestamp, chief_complaint text, present_illness_history text, past_medical_history text, physical_examination_notes text, assessment text, treatment_plan text, vitals text, created_at timestamp )

[User] List all medical records created by doctor 'doctor_001' for patients who had their last medical record on or after '2024-01-01', including record_id, patient_id, record_date, chief_complaint, and doctor_id.

[Assistant]
SELECT mr.record_id, mr.patient_id, mr.record_date, mr.chief_complaint, mr.doctor_id
FROM healthcare.medical_records mr
JOIN (
    SELECT patient_id, MAX(record_date) AS last_record_date
    FROM healthcare.medical_records
    GROUP BY patient_id
) last_rec ON mr.patient_id = last_rec.patient_id
WHERE mr.doctor_id = 'doctor_001' AND last_rec.last_record_date >= '2024-01-01';

[User] Please refine the results to only include records where the 'assessment' field is not null.

[Assistant]
SELECT mr.record_id, mr.patient_id, mr.record_date, mr.chief_complaint, mr.doctor_id
FROM healthcare.medical_records mr
JOIN (
    SELECT patient_id, MAX(record_date) AS last_record_date
    FROM healthcare.medical_records
    GROUP BY patient_id
) last_rec ON mr.patient_id = last_rec.patient_id
WHERE mr.doctor_id = 'doctor_001' AND last_rec.last_record_date >= '2024-01-01' AND mr.assessment IS NOT NULL;

[User] I received too many results. Can you only show records where 'treatment_plan' is also not null?

[Assistant]
SELECT mr.record_id, mr.patient_id, mr.record_date, mr.chief_complaint, mr.doctor_id
FROM healthcare.medical_records mr
JOIN (
    SELECT patient_id, MAX(record_date) AS last_record_date
    FROM healthcare.medical_records
    GROUP BY patient_id
) last_rec ON mr.patient_id = last_rec.patient_id
WHERE mr.doctor_id = 'doctor_001' AND last_rec.last_record_date >= '2024-01-01' AND mr.assessment IS NOT NULL AND mr.treatment_plan IS NOT NULL;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE healthcare.medications ( medication_id text PRIMARY KEY, medication_name text, generic_name text, manufacturer text, ndc_code text, description text )

[User] List the medication IDs and names for all entries where the description is missing or empty.

[Assistant] SELECT medication_id, medication_name FROM healthcare.medications WHERE description IS NULL OR description = '';

[User] For those medications, please also show the manufacturer and sort the results by medication name in ascending order.

[Assistant] SELECT medication_id, medication_name, manufacturer FROM healthcare.medications WHERE description IS NULL OR description = '' ORDER BY medication_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 healthcare.patients ( patient_id text, first_name text, last_name text, date_of_birth date, gender text, address text, phone_number text, email text, emergency_contact_name text, emergency_contact_phone text, created_at timestamp, updated_at timestamp )
CREATE TABLE healthcare.appointments ( appointment_id text, patient_id text, doctor_id text, appointment_time timestamp, duration_minutes integer, reason text, status text, location_id text, notes text, created_at timestamp )
CREATE TABLE healthcare.medical_records ( record_id text, patient_id text, appointment_id text, doctor_id text, record_date timestamp, chief_complaint text, present_illness_history text, past_medical_history text, physical_examination_notes text, assessment text, treatment_plan text, vitals text, created_at timestamp )
CREATE TABLE healthcare.diagnoses ( diagnosis_id text, record_id text, patient_id text, doctor_id text, diagnosis_code text, code_type text, description text, diagnosis_date date, status text, is_chronic boolean )
CREATE TABLE healthcare.medications ( medication_id text, medication_name text, generic_name text, manufacturer text, ndc_code text, description text )
CREATE TABLE healthcare.prescriptions ( prescription_id text, record_id text, patient_id text, doctor_id text, medication_id text, dosage text, frequency text, route text, start_date date, end_date date, quantity_dispensed numeric, refills_allowed integer, prescription_date timestamp )
CREATE TABLE healthcare.insurance_plans ( plan_id text, plan_name text, insurance_provider text, plan_type text, contact_phone text, website text )
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] I need to find patients who received prescriptions within 7 days after their latest appointment. Show patient_id, first and last name, appointment_time, prescription_date, and medication_name.

[Assistant]
WITH latest_appt AS (
  SELECT patient_id, MAX(appointment_time) AS latest_time
  FROM healthcare.appointments
  GROUP BY patient_id
)
SELECT p.patient_id,
       p.first_name,
       p.last_name,
       la.latest_time AS appointment_time,
       pr.prescription_date,
       m.medication_name
FROM latest_appt la
JOIN healthcare.patients p
  ON p.patient_id = la.patient_id
JOIN healthcare.prescriptions pr
  ON pr.patient_id = la.patient_id
  AND pr.prescription_date BETWEEN la.latest_time AND la.latest_time + INTERVAL '7 days'
JOIN healthcare.medications m
  ON m.medication_id = pr.medication_id

[User] Actually, restrict it to prescriptions where dosage contains 'mg'.

[Assistant]
WITH latest_appt AS (
  SELECT patient_id, MAX(appointment_time) AS latest_time
  FROM healthcare.appointments
  GROUP BY patient_id
)
SELECT p.patient_id,
       p.first_name,
       p.last_name,
       la.latest_time AS appointment_time,
       pr.prescription_date,
       m.medication_name
FROM latest_appt la
JOIN healthcare.patients p
  ON p.patient_id = la.patient_id
JOIN healthcare.prescriptions pr
  ON pr.patient_id = la.patient_id
  AND pr.prescription_date BETWEEN la.latest_time AND la.latest_time + INTERVAL '7 days'
  AND pr.dosage LIKE '%mg%'
JOIN healthcare.medications m
  ON m.medication_id = pr.medication_id

[User] Also, sort the results by prescription_date descending and limit to 5.

[Assistant]
WITH latest_appt AS (
  SELECT patient_id, MAX(appointment_time) AS latest_time
  FROM healthcare.appointments
  GROUP BY patient_id
)
SELECT p.patient_id,
       p.first_name,
       p.last_name,
       la.latest_time AS appointment_time,
       pr.prescription_date,
       m.medication_name
FROM latest_appt la
JOIN healthcare.patients p
  ON p.patient_id = la.patient_id
JOIN healthcare.prescriptions pr
  ON pr.patient_id = la.patient_id
  AND pr.prescription_date BETWEEN la.latest_time AND la.latest_time + INTERVAL '7 days'
  AND pr.dosage LIKE '%mg%'
JOIN healthcare.medications m
  ON m.medication_id = pr.medication_id
ORDER BY pr.prescription_date DESC
LIMIT 5


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE healthcare.doctors ( doctor_id text, 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.appointments ( appointment_id text, patient_id text, doctor_id text, appointment_time timestamp, duration_minutes integer, reason text, status text, location_id text, notes text, created_at timestamp )
CREATE TABLE healthcare.medical_records ( record_id text, patient_id text, appointment_id text, doctor_id text, record_date timestamp, chief_complaint text, present_illness_history text, past_medical_history text, physical_examination_notes text, assessment text, treatment_plan text, vitals text, created_at timestamp )
CREATE TABLE healthcare.diagnoses ( diagnosis_id text, record_id text, patient_id text, doctor_id text, diagnosis_code text, code_type text, description text, diagnosis_date date, status text, is_chronic boolean )
CREATE TABLE healthcare.medications ( medication_id text, medication_name text, generic_name text, manufacturer text, ndc_code text, description text )
CREATE TABLE healthcare.insurance_plans ( plan_id text, plan_name text, insurance_provider text, plan_type text, contact_phone text, website text )
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] Show a list of patients along with their most recent diagnoses, including patient ID, diagnosis description, and the diagnosis date.

[Assistant] SELECT d.patient_id, d.description AS diagnosis_description, d.diagnosis_date FROM healthcare.diagnoses d INNER JOIN (SELECT patient_id, MAX(diagnosis_date) AS latest_date FROM healthcare.diagnoses GROUP BY patient_id) latest ON d.patient_id = latest.patient_id AND d.diagnosis_date = latest.latest_date;

[User] Add the doctor's full name who made each diagnosis to the results.

[Assistant] SELECT d.patient_id, doc.first_name || ' ' || doc.last_name AS doctor_full_name, d.description AS diagnosis_description, d.diagnosis_date FROM healthcare.diagnoses d INNER JOIN (SELECT patient_id, MAX(diagnosis_date) AS latest_date FROM healthcare.diagnoses GROUP BY patient_id) latest ON d.patient_id = latest.patient_id AND d.diagnosis_date = latest.latest_date INNER JOIN healthcare.doctors doc ON d.doctor_id = doc.doctor_id;

[User] Could you also include the diagnosis code in the output?

[Assistant] SELECT d.patient_id, doc.first_name || ' ' || doc.last_name AS doctor_full_name, d.diagnosis_code, d.description AS diagnosis_description, d.diagnosis_date FROM healthcare.diagnoses d INNER JOIN (SELECT patient_id, MAX(diagnosis_date) AS latest_date FROM healthcare.diagnoses GROUP BY patient_id) latest ON d.patient_id = latest.patient_id AND d.diagnosis_date = latest.latest_date INNER JOIN healthcare.doctors doc ON d.doctor_id = doc.doctor_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.patients ( patient_id.text, first_name.text, last_name.text, date_of_birth.date, gender.text, address.text, phone_number.text, email.text, emergency_contact_name.text, emergency_contact_phone.text, created_at.timestamp, updated_at.timestamp )
CREATE TABLE healthcare.appointments ( appointment_id.text, patient_id.text, doctor_id.text, appointment_time.timestamp, duration_minutes.integer, reason.text, status.text, location_id.text, notes.text, created_at.timestamp )

[User] I need a count of appointments per patient that took place between '2024-04-01' and '2024-04-30', showing patient_id, first_name, last_name, and the total number of appointments.

[Assistant]
SELECT p.patient_id, p.first_name, p.last_name, COUNT(a.appointment_id) AS appointment_count
FROM healthcare.patients p
JOIN healthcare.appointments a ON p.patient_id = a.patient_id
WHERE a.appointment_time BETWEEN '2024-04-01' AND '2024-04-30'
GROUP BY p.patient_id, p.first_name, p.last_name;

[User] Only include patients who had at least 2 appointments in that period.

[Assistant]
SELECT p.patient_id, p.first_name, p.last_name, COUNT(a.appointment_id) AS appointment_count
FROM healthcare.patients p
JOIN healthcare.appointments a ON p.patient_id = a.patient_id
WHERE a.appointment_time BETWEEN '2024-04-01' AND '2024-04-30'
GROUP BY p.patient_id, p.first_name, p.last_name
HAVING COUNT(a.appointment_id) >= 2;


[User] Find all medications whose NDC code starts with '0003'. Show the medication ID and NDC code.

[Assistant] SELECT medication_id, ndc_code FROM healthcare.medications WHERE ndc_code LIKE '0003%';

[User] Count the number of medications for each manufacturer and show manufacturers with more than 100 medications.

[Assistant] SELECT manufacturer, COUNT(*) AS medication_count FROM healthcare.medications GROUP BY manufacturer HAVING COUNT(*) > 100;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE hospitality_technology.properties ( property_id text PRIMARY KEY, property_name text, address_line1 text, address_line2 text, city text, state_province text, postal_code text, country_code text, phone_number text, email_address text, property_type text, star_rating numeric, timezone text, manager_staff_id text, created_at timestamp, updated_at timestamp )
CREATE TABLE hospitality_technology.rooms (
    room_id character varying(64) NOT NULL,  -- unique identifier for the room
    property_id character varying(64) NOT NULL, -- FK to properties table
    room_number character varying(10) NOT NULL, -- room number identifier (e.g., '101', 'Suite 2B')
    room_type_id character varying(64) NOT NULL, -- FK to room_types table
    floor integer, -- floor number the room is on
    status character varying(50) NOT NULL, -- e.g., Available, Occupied, Cleaning, OutOfOrder, Maintenance
    is_smoking boolean NOT NULL DEFAULT false, -- smoking allowed flag
    features text, -- description of features (e.g., Balcony, Sea View, Jacuzzi)
    current_condition text, -- notes on room condition
    last_cleaned_at timestamp with time zone, -- timestamp of last cleaning
    PRIMARY KEY (room_id),
    FOREIGN KEY (property_id) REFERENCES hospitality_technology.properties(property_id),
    FOREIGN KEY (room_type_id) REFERENCES hospitality_technology.room_types(room_type_id)
)
CREATE TABLE hospitality_technology.room_types (
    room_type_id character varying(64) NOT NULL, -- unique identifier for the room type
    property_id character varying(64) NOT NULL, -- FK to properties table (type might be property-specific)
    type_name character varying(100) NOT NULL, -- e.g., Standard King, Deluxe Queen, Executive Suite
    description text, -- description of the room type
    base_rate numeric(10, 2) NOT NULL, -- standard price per night
    max_occupancy integer NOT NULL, -- maximum number of guests
    bed_type character varying(50), -- e.g., King, Queen, 2 Doubles, Twin
    area_sqft numeric(8,2), -- size of the room in square feet
    amenities text, -- comma-separated list or JSON of amenities
    PRIMARY KEY (room_type_id),
    FOREIGN KEY (property_id) REFERENCES hospitality_technology.properties(property_id)
)
CREATE TABLE hospitality_technology.guests ( guest_id.text, first_name.text, last_name.text, email.text, phone_number.text, date_of_birth.date, address_line1.text, city.text, state_province.text, postal_code.text, country_code.text, preferences.text, loyalty_member_id.text, communication_consent.boolean, created_at.timestamp, updated_at.timestamp )
CREATE TABLE hospitality_technology.reservations ( reservation_id text, property_id text, guest_id text, room_id text, room_type_id text, check_in_date date, check_out_date date, actual_check_in_ts timestamp, actual_check_out_ts timestamp, num_adults integer, num_children integer, status text, booking_source text, rate_plan_id text, total_amount numeric, amount_paid numeric, special_requests text, created_at timestamp, updated_at timestamp )
CREATE TABLE hospitality_technology.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 )
CREATE TABLE hospitality_technology.reviews (
    review_id character varying(64) NOT NULL,  -- unique identifier for the review
    property_id character varying(64) NOT NULL, -- FK to properties table
    reservation_id character varying(64) UNIQUE, -- FK to reservations (link review to a specific stay, optional but good)
    guest_id character varying(64) NOT NULL, -- FK to guests table
    rating_overall integer, -- overall score (e.g., 1-5 or 1-10)
    rating_cleanliness integer,
    rating_service integer,
    rating_location integer,
    rating_value integer,
    comment text, -- guest's written feedback
    review_source character varying(100), -- e.g., DirectSurvey, TripAdvisor, Google, Booking.com
    review_date timestamp with time zone NOT NULL DEFAULT current_timestamp, -- when the review was submitted
    is_public boolean DEFAULT true, -- whether the review is publicly visible
    staff_response text, -- official response from the property
    response_staff_id character varying(64), -- FK to staff (who responded)
    response_date timestamp with time zone, -- when the response was posted
    PRIMARY KEY (review_id),
    FOREIGN KEY (property_id) REFERENCES hospitality_technology.properties(property_id),
    FOREIGN KEY (reservation_id) REFERENCES hospitality_technology.reservations(reservation_id),
    FOREIGN KEY (guest_id) REFERENCES hospitality_technology.guests(guest_id),
    FOREIGN KEY (response_staff_id) REFERENCES hospitality_technology.staff(staff_id)
)

[User] For each reservation in the last three months, show the reservation ID, check-in date, number of adults, and the corresponding room type name.

[Assistant]
SELECT r.reservation_id, r.check_in_date, r.num_adults, rt.type_name
FROM hospitality_technology.reservations r
JOIN hospitality_technology.room_types rt ON r.room_type_id = rt.room_type_id
WHERE r.created_at >= NOW() - INTERVAL '3 months';

[User] Also include the name of the property for each reservation.

[Assistant]
SELECT r.reservation_id, r.check_in_date, r.num_adults, rt.type_name, p.property_name
FROM hospitality_technology.reservations r
JOIN hospitality_technology.room_types rt ON r.room_type_id = rt.room_type_id
JOIN hospitality_technology.properties p ON r.property_id = p.property_id
WHERE r.created_at >= NOW() - INTERVAL '3 months';

[User] Sort the results by number of adults descending, and then by check-in date ascending.

[Assistant]
SELECT r.reservation_id, r.check_in_date, r.num_adults, rt.type_name, p.property_name
FROM hospitality_technology.reservations r
JOIN hospitality_technology.room_types rt ON r.room_type_id = rt.room_type_id
JOIN hospitality_technology.properties p ON r.property_id = p.property_id
WHERE r.created_at >= NOW() - INTERVAL '3 months'
ORDER BY r.num_adults DESC, r.check_in_date ASC;