System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE social_media.users (
    user_id character varying(64) NOT NULL,  -- unique identifier for the user
    username character varying(50) NOT NULL UNIQUE, -- user's unique handle
    email character varying(128) NOT NULL UNIQUE, -- user's email address
    password_hash text NOT NULL, -- hashed password
    full_name character varying(100), -- user's full name
    profile_picture_url text, -- URL to the profile picture
    bio text, -- short user biography
    location character varying(100), -- user's location
    created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, -- timestamp of account creation
    updated_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, -- timestamp of last profile update
    is_verified boolean NOT NULL DEFAULT false, -- verification status
    PRIMARY KEY (user_id)
)
CREATE TABLE social_media.posts (
    post_id character varying(64) NOT NULL, -- unique identifier for the post
    user_id character varying(64) NOT NULL, -- identifier of the user who created the post (FK to users.user_id)
    content text, -- textual content of the post
    media_url text, -- URL to attached media (image/video)
    media_type character varying(20), -- type of media ('image', 'video', null)
    created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, -- timestamp of post creation
    updated_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, -- timestamp of last post edit
    visibility character varying(20) NOT NULL DEFAULT 'public', -- visibility ('public', 'friends', 'private')
    location_lat numeric(9,6), -- latitude of post location
    location_lon numeric(9,6), -- longitude of post location
    PRIMARY KEY (post_id)
)
CREATE TABLE social_media.comments (
    comment_id character varying(64) NOT NULL, -- unique identifier for the comment
    post_id character varying(64) NOT NULL, -- identifier of the post being commented on (FK to posts.post_id)
    user_id character varying(64) NOT NULL, -- identifier of the user who made the comment (FK to users.user_id)
    parent_comment_id character varying(64), -- identifier of the parent comment if it's a reply (FK to comments.comment_id)
    content text NOT NULL, -- textual content of the comment
    created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, -- timestamp of comment creation
    updated_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, -- timestamp of last comment edit
    PRIMARY KEY (comment_id)
)
CREATE TABLE social_media.likes (
    like_id character varying(64) NOT NULL, -- unique identifier for the like
    user_id character varying(64) NOT NULL, -- identifier of the user who liked (FK to users.user_id)
    post_id character varying(64), -- identifier of the post being liked (FK to posts.post_id, nullable)
    comment_id character varying(64), -- identifier of the comment being liked (FK to comments.comment_id, nullable)
    created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, -- timestamp of when the like occurred
    PRIMARY KEY (like_id),
    CONSTRAINT unique_user_like UNIQUE (user_id, post_id, comment_id), -- prevent duplicate likes
    CONSTRAINT check_like_target CHECK (post_id IS NOT NULL OR comment_id IS NOT NULL) -- ensure it likes something
)
CREATE TABLE social_media.follows (
    follow_id character varying(64) NOT NULL, -- unique identifier for the follow relationship
    follower_user_id character varying(64) NOT NULL, -- identifier of the user who is following (FK to users.user_id)
    following_user_id character varying(64) NOT NULL, -- identifier of the user being followed (FK to users.user_id)
    created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, -- timestamp of when the follow started
    PRIMARY KEY (follow_id),
    CONSTRAINT unique_follow UNIQUE (follower_user_id, following_user_id) -- prevent duplicate follows
)
CREATE TABLE social_media.hashtags (
    hashtag_id character varying(64) NOT NULL, -- unique identifier for the hashtag
    tag_name character varying(100) NOT NULL UNIQUE, -- the actual hashtag text (without '#')
    created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, -- timestamp when the hashtag was first used
    PRIMARY KEY (hashtag_id)
)
CREATE TABLE social_media.messages (
    message_id character varying(64) NOT NULL, -- unique identifier for the message
    conversation_id character varying(64) NOT NULL, -- identifier for the conversation thread (FK to conversations.conversation_id)
    sender_user_id character varying(64) NOT NULL, -- identifier of the sender (FK to users.user_id)
    content text, -- textual content of the message
    media_url text, -- URL to attached media (image/video)
    media_type character varying(20), -- type of media ('image', 'video', null)
    sent_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, -- timestamp when message was sent
    read_at timestamp, -- timestamp when message was read by recipient(s)
    PRIMARY KEY (message_id)
)
CREATE TABLE social_media.conversations (
    conversation_id character varying(64) NOT NULL, -- unique identifier for the conversation
    created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, -- timestamp when conversation was initiated
    last_message_at timestamp, -- timestamp of the last message in the conversation
    is_group_chat boolean NOT NULL DEFAULT false, -- indicates if it's a group chat or direct message
    group_name character varying(100), -- name of the group chat (if applicable)
    PRIMARY KEY (conversation_id)
)
CREATE TABLE social_media.conversation_participants (
    participant_id character varying(64) NOT NULL, -- unique identifier for the participant entry
    conversation_id character varying(64) NOT NULL, -- identifier of the conversation (FK to conversations.conversation_id)
    user_id character varying(64) NOT NULL, -- identifier of the user in the conversation (FK to users.user_id)
    joined_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, -- timestamp when user joined the conversation
    last_read_at timestamp, -- timestamp indicating up to when the user has read messages
    PRIMARY KEY (participant_id),
    CONSTRAINT unique_user_conversation UNIQUE (conversation_id, user_id) -- prevent user being added multiple times
)
CREATE TABLE social_media.notifications (
    notification_id character varying(64) NOT NULL, -- unique identifier for the notification
    recipient_user_id character varying(64) NOT NULL, -- user receiving the notification (FK to users.user_id)
    sender_user_id character varying(64), -- user triggering the notification (FK to users.user_id, can be null for system notifications)
    notification_type character varying(30) NOT NULL, -- type of notification ('like', 'comment', 'follow', 'mention', 'message')
    target_entity_id character varying(64), -- ID of the related entity (post_id, comment_id, user_id, conversation_id)
    target_entity_type character varying(20), -- type of the related entity ('post', 'comment', 'user', 'conversation')
    created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, -- timestamp notification was created
    read_at timestamp, -- timestamp notification was marked as read
    PRIMARY KEY (notification_id)
)
CREATE TABLE social_media.user_settings (
    setting_id character varying(64) NOT NULL, -- unique identifier for the setting entry
    user_id character varying(64) NOT NULL UNIQUE, -- user the settings belong to (FK to users.user_id)
    theme character varying(20) DEFAULT 'light', -- UI theme ('light', 'dark')
    email_notifications_enabled boolean DEFAULT true, -- enable/disable email notifications
    push_notifications_enabled boolean DEFAULT true, -- enable/disable push notifications
    private_profile boolean DEFAULT false, -- is the user profile private
    updated_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, -- timestamp of last setting change
    PRIMARY KEY (setting_id)
)

[User] List users who commented on posts and the content of the post they commented on. Show commenter username and post content.

[Assistant] SELECT T1.username, T2.content FROM social_media.users AS T1 JOIN social_media.comments AS T3 ON T1.user_id = T3.user_id JOIN social_media.posts AS T2 ON T3.post_id = T2.post_id;

[User] Now, only include those users who also liked the specific post they commented on.

[Assistant] SELECT T1.username, T2.content FROM social_media.users AS T1 JOIN social_media.comments AS T3 ON T1.user_id = T3.user_id JOIN social_media.posts AS T2 ON T3.post_id = T2.post_id JOIN social_media.likes AS T4 ON T1.user_id = T4.user_id AND T2.post_id = T4.post_id;

[User] Show me the usernames and full names of all users who have liked at least one post that was created in May 2024.

[Assistant]
SELECT DISTINCT u.username, u.full_name
FROM social_media.users u
JOIN social_media.likes l ON u.user_id = l.user_id
JOIN social_media.posts p ON l.post_id = p.post_id
WHERE p.created_at >= '2024-05-01' AND p.created_at < '2024-06-01';

[User] Some of these users appear multiple times. Can you also include the count of distinct posts they have liked from May 2024, as liked_posts_count?

[Assistant]
SELECT u.username, u.full_name, COUNT(DISTINCT p.post_id) AS liked_posts_count
FROM social_media.users u
JOIN social_media.likes l ON u.user_id = l.user_id
JOIN social_media.posts p ON l.post_id = p.post_id
WHERE p.created_at >= '2024-05-01' AND p.created_at < '2024-06-01'
GROUP BY u.user_id, u.username, u.full_name;

[User] Now, only show users who have liked more than 2 distinct posts from May 2024 and order them by liked_posts_count descending.

[Assistant]
SELECT u.username, u.full_name, COUNT(DISTINCT p.post_id) AS liked_posts_count
FROM social_media.users u
JOIN social_media.likes l ON u.user_id = l.user_id
JOIN social_media.posts p ON l.post_id = p.post_id
WHERE p.created_at >= '2024-05-01' AND p.created_at < '2024-06-01'
GROUP BY u.user_id, u.username, u.full_name
HAVING COUNT(DISTINCT p.post_id) > 2
ORDER BY liked_posts_count DESC;

[User] Show me the usernames and email addresses for users who have a non-empty bio and are verified.

[Assistant] SELECT username, email FROM social_media.users WHERE bio IS NOT NULL AND bio != '' AND is_verified = TRUE;

[User] For each user, show their username, email, and the number of posts they've created that contain at least one hashtag. Only include users who have created such posts.

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

[User] Actually, I'd like to see, for each user, the total number of unique hashtags they've used across their posts too. Please include that as unique_hashtags_count.

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

[User] List all group chats created in 2024, showing the group_name, conversation_id, and creation time.

[Assistant]
SELECT conversation_id, group_name, created_at
FROM social_media.conversations
WHERE is_group_chat = true AND created_at >= '2024-01-01' AND created_at < '2025-01-01';

[User] Count the number of posts that have a media URL but no textual content.

[Assistant] SELECT COUNT(*) FROM social_media.posts AS T1 WHERE T1.media_url IS NOT NULL AND (T1.content IS NULL OR T1.content = '');


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.services ( service_id character varying(64) NOT NULL, property_id character varying(64) NOT NULL, service_name character varying(150) NOT NULL, description text, category character varying(100), price numeric(10, 2) NOT NULL, unit character varying(30), is_available boolean NOT NULL DEFAULT true, department character varying(100), PRIMARY KEY (service_id), FOREIGN KEY (property_id) REFERENCES hospitality_technology.properties(property_id) )

[User] List all available services along with the property name where they are offered.

[Assistant]
SELECT s.service_id, s.service_name, p.property_name
FROM hospitality_technology.services s
JOIN hospitality_technology.properties p ON s.property_id = p.property_id
WHERE s.is_available = true;

[User] Show me each department in each property, along with the total number of available services and their combined price.

[Assistant] SELECT property_id, department, COUNT(*) AS service_count, SUM(price) AS total_price FROM hospitality_technology.services WHERE is_available = true GROUP BY property_id, department;

[User] Give me a breakdown of available services by unit, with the count of services and the average price, grouped by property.

[Assistant] SELECT property_id, unit, COUNT(*) AS service_count, AVG(price) AS avg_price FROM hospitality_technology.services WHERE is_available = true GROUP BY property_id, unit;

[User] I only want results where the average price is above 50.

[Assistant] SELECT property_id, unit, COUNT(*) AS service_count, AVG(price) AS avg_price FROM hospitality_technology.services WHERE is_available = true GROUP BY property_id, unit HAVING AVG(price) > 50;

[User] Actually, also include the department for each unit in the result.

[Assistant] SELECT property_id, unit, department, COUNT(*) AS service_count, AVG(price) AS avg_price FROM hospitality_technology.services WHERE is_available = true GROUP BY property_id, unit, department HAVING AVG(price) > 50;

[User] List all properties and the count of their available services in the 'Activities' category.

[Assistant] SELECT T2.property_name, COUNT(T1.service_id) AS available_activities_count FROM hospitality_technology.services AS T1 JOIN hospitality_technology.properties AS T2 ON T1.property_id = T2.property_id WHERE T1.is_available = TRUE AND T1.category = 'Activities' GROUP BY T2.property_id, T2.property_name;

[User] Now, only show properties with more than 3 available 'Activities' services.

[Assistant] SELECT T2.property_name, COUNT(T1.service_id) AS available_activities_count FROM hospitality_technology.services AS T1 JOIN hospitality_technology.properties AS T2 ON T1.property_id = T2.property_id WHERE T1.is_available = TRUE AND T1.category = 'Activities' GROUP BY T2.property_id, T2.property_name HAVING COUNT(T1.service_id) > 3;

[User] Sort the results by the count of services descending.

[Assistant] SELECT T2.property_name, COUNT(T1.service_id) AS available_activities_count FROM hospitality_technology.services AS T1 JOIN hospitality_technology.properties AS T2 ON T1.property_id = T2.property_id WHERE T1.is_available = TRUE AND T1.category = 'Activities' GROUP BY T2.property_id, T2.property_name HAVING COUNT(T1.service_id) > 3 ORDER BY available_activities_count DESC;

[User] List all services provided by the property named 'Grand Plaza Hotel' and include their category and price.

[Assistant] SELECT T1.service_name, T1.category, T1.price FROM hospitality_technology.services AS T1 JOIN hospitality_technology.properties AS T2 ON T1.property_id = T2.property_id WHERE T2.property_name = 'Grand Plaza Hotel';

[User] Only show available services from the 'Spa' department at 'Grand Plaza Hotel'.

[Assistant] SELECT T1.service_name, T1.category, T1.price FROM hospitality_technology.services AS T1 JOIN hospitality_technology.properties AS T2 ON T1.property_id = T2.property_id WHERE T2.property_name = 'Grand Plaza Hotel' AND T1.is_available = TRUE AND T1.department = 'Spa';

[User] For each property, show the property name, average price of available services, and the maximum price of available services.

[Assistant]
SELECT p.property_name,
       AVG(s.price) AS avg_price,
       MAX(s.price) AS max_price
FROM hospitality_technology.services s
JOIN hospitality_technology.properties p ON s.property_id = p.property_id
WHERE s.is_available = true
GROUP BY p.property_name;

[User] Actually, I also need the service_name of the highest priced available service per property.

[Assistant]
SELECT t.property_name,
       t.avg_price,
       s_high.service_name AS highest_priced_service,
       t.max_price
FROM (
    SELECT s.property_id,
           p.property_name,
           AVG(s.price) AS avg_price,
           MAX(s.price) AS max_price
    FROM hospitality_technology.services s
    JOIN hospitality_technology.properties p ON s.property_id = p.property_id
    WHERE s.is_available = true
    GROUP BY s.property_id, p.property_name
) t
JOIN hospitality_technology.services s_high
  ON s_high.property_id = t.property_id
 AND s_high.price = t.max_price
 AND s_high.is_available = true;

[User] Now, only include properties where the average price is above 75 and sort the results by avg_price descending.

[Assistant]
SELECT t.property_name,
       t.avg_price,
       s_high.service_name AS highest_priced_service,
       t.max_price
FROM (
    SELECT s.property_id,
           p.property_name,
           AVG(s.price) AS avg_price,
           MAX(s.price) AS max_price
    FROM hospitality_technology.services s
    JOIN hospitality_technology.properties p ON s.property_id = p.property_id
    WHERE s.is_available = true
    GROUP BY s.property_id, p.property_name
    HAVING AVG(s.price) > 75
) t
JOIN hospitality_technology.services s_high
  ON s_high.property_id = t.property_id
 AND s_high.price = t.max_price
 AND s_high.is_available = true
ORDER BY t.avg_price 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.insurance_products ( product_id text PRIMARY KEY, product_name text, product_type text, description text, base_premium numeric, coverage_details text, underwriting_rules text, is_active boolean, created_at timestamp, updated_at timestamp )

[User] Get the number of insurance products grouped by product_type and their active status. Return product_type, is_active, and the count of products.

[Assistant]
SELECT product_type, is_active, COUNT(*) AS product_count
FROM insurance.insurance_products
GROUP BY product_type, is_active;

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

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

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

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

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

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

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

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

[User] List all pairs of insurance products that share the same product_type but have differing active statuses. Return both product_ids, the product_type, and each is_active flag.

[Assistant]
SELECT p1.product_id AS product_id_1, p2.product_id AS product_id_2, p1.product_type, p1.is_active AS is_active_1, p2.is_active AS is_active_2
FROM insurance.insurance_products p1
JOIN insurance.insurance_products p2
  ON p1.product_type = p2.product_type
  AND p1.is_active <> p2.is_active
WHERE p1.product_id < p2.product_id;

[User] Which insurance products have 'comprehensive' in their coverage details? Show the product_id and product_name.

[Assistant] SELECT product_id, product_name FROM insurance.insurance_products WHERE coverage_details ILIKE '%comprehensive%';

[User] Can you also add the product_type to the output?

[Assistant] SELECT product_id, product_name, product_type FROM insurance.insurance_products WHERE coverage_details ILIKE '%comprehensive%';

[User] Give me the product name and description of all insurance products that have been updated in the last 30 days.

[Assistant] SELECT product_name, description FROM insurance.insurance_products WHERE updated_at >= NOW() - INTERVAL '30 days';

[User] Retrieve the count of active insurance products for each product_type and order the results by the count descending.

[Assistant]
SELECT product_type,
       COUNT(*) AS active_count
FROM insurance.insurance_products
WHERE is_active = TRUE
GROUP BY product_type
ORDER BY active_count DESC;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE government_services.citizens ( citizen_id text PRIMARY KEY, national_id_number text, first_name text, last_name text, date_of_birth date, gender text, primary_address text, contact_email text, contact_phone text, registration_date timestamp, is_verified boolean )
CREATE TABLE government_services.applications ( application_id text PRIMARY KEY, citizen_id text, service_id text, submitted_at timestamp, status text, last_updated_at timestamp, assigned_employee_id text, decision_date date, notes text, reference_number text )
CREATE TABLE government_services.payments ( payment_id text PRIMARY KEY, application_id text, citizen_id text, service_id text, amount numeric, currency text, payment_method text, payment_provider_reference text, payment_timestamp timestamp, status text, notes text )
CREATE TABLE government_services.service_locations ( location_id text PRIMARY KEY, agency_id text, location_name text, address text, city text, state text, postal_code text, latitude numeric, longitude numeric, operating_hours text, contact_phone text, is_accessible boolean )
CREATE TABLE government_services.appointments ( appointment_id text PRIMARY KEY, citizen_id text, employee_id text, location_id text, service_id text, scheduled_start_time timestamp, scheduled_end_time timestamp, purpose text, status text, booking_method text, created_at timestamp, notes text )
CREATE TABLE government_services.notifications ( notification_id text PRIMARY KEY, citizen_id text, application_id text, message_subject text, message_body text, channel text, sent_at timestamp, status text, related_entity_type text, related_entity_id text )

[User] Show the full names and contact emails of all citizens who have made a payment for an application that is currently in 'Pending' status.

[Assistant]
SELECT DISTINCT c.first_name || ' ' || c.last_name AS full_name, c.contact_email
FROM government_services.citizens c
JOIN government_services.payments p ON c.citizen_id = p.citizen_id
JOIN government_services.applications a ON p.application_id = a.application_id
WHERE a.status = 'Pending';

[User] Show the appointment ID, scheduled start time, and the full name of the citizen for all appointments related to services with a standard fee greater than 150.

[Assistant]
SELECT a.appointment_id, a.scheduled_start_time, c.first_name || ' ' || c.last_name AS full_name
FROM government_services.appointments a
JOIN government_services.citizens c ON a.citizen_id = c.citizen_id
JOIN government_services.payments p ON a.citizen_id = p.citizen_id AND a.service_id = p.service_id
WHERE p.amount > 150;

[User] How many payments were made using the payment method 'Credit Card'?

[Assistant]
SELECT COUNT(*) AS credit_card_payments
FROM government_services.payments
WHERE payment_method = 'Credit Card';

[User] For each notification sent through the 'SMS' channel, list the notification ID, message subject, and the full name of the citizen who received it.

[Assistant]
SELECT n.notification_id, n.message_subject, c.first_name || ' ' || c.last_name AS full_name
FROM government_services.notifications n
JOIN government_services.citizens c ON n.citizen_id = c.citizen_id
WHERE n.channel = 'SMS';

[User] Which citizens have submitted applications for services that belong to the 'Education' category? List the citizen's full name, the service name, and the application ID.

[Assistant]
SELECT c.first_name || ' ' || c.last_name AS full_name, s.service_name, a.application_id
FROM government_services.applications a
JOIN government_services.citizens c ON a.citizen_id = c.citizen_id
JOIN government_services.services s ON a.service_id = s.service_id
WHERE s.category = 'Education';

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

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


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE 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 PRIMARY KEY, name text, country text, founded_year int, website text, created_at timestamptz )
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 )
CREATE TABLE gaming_technology.servers ( server_id uuid PRIMARY KEY, game_id uuid, server_name text, region text, ip_address text, port int, current_players int, max_players int, status text, last_heartbeat timestamptz )
CREATE TABLE gaming_technology.achievements ( achievement_id uuid PRIMARY KEY, game_id uuid, name text, description text, icon_url text, points int, hidden boolean )
CREATE TABLE gaming_technology.player_achievements ( player_achievement_id uuid PRIMARY KEY, player_id uuid, achievement_id uuid, unlocked_at timestamptz )
CREATE TABLE gaming_technology.in_game_items ( item_id uuid PRIMARY KEY, game_id uuid, item_name text, item_type text, description text, rarity text, cost_currency text, cost_amount numeric, attributes jsonb )
CREATE TABLE gaming_technology.player_inventory ( inventory_id uuid PRIMARY KEY, player_id uuid, item_id uuid, quantity int, acquired_at timestamptz, instance_data jsonb )

[User] Show me the title of each game and the total number of game sessions played on servers hosting that game.

[Assistant] SELECT t1.title, count(t3.session_id) FROM gaming_technology.games AS t1 JOIN gaming_technology.servers AS t2 ON t1.game_id = t2.game_id JOIN gaming_technology.game_sessions AS t3 ON t2.server_id = t3.server_id GROUP BY 1

[User] Now, filter this list to only include games with more than 1000 total sessions, and order the results by session count descending.

[Assistant] SELECT t1.title, count(t3.session_id) FROM gaming_technology.games AS t1 JOIN gaming_technology.servers AS t2 ON t1.game_id = t2.game_id JOIN gaming_technology.game_sessions AS t3 ON t2.server_id = t3.server_id GROUP BY 1 HAVING count(t3.session_id) > 1000 ORDER BY count(t3.session_id) DESC

[User] Find all in-game items that have a 'mana_cost' attribute in their attributes JSON. Show the item ID, item name, and the value of the 'mana_cost'.

[Assistant] SELECT item_id, item_name, attributes ->> 'mana_cost' AS mana_cost FROM gaming_technology.in_game_items WHERE attributes ? 'mana_cost'

[User] Now, only include items where the 'mana_cost' is greater than 50.

[Assistant] SELECT item_id, item_name, attributes ->> 'mana_cost' AS mana_cost FROM gaming_technology.in_game_items WHERE attributes ? 'mana_cost' AND (attributes ->> 'mana_cost')::int > 50

[User] Add the item's rarity and the title of the game it belongs to in the output.

[Assistant] SELECT t1.item_id, t1.item_name, t1.rarity, t2.title, t1.attributes ->> 'mana_cost' AS mana_cost FROM gaming_technology.in_game_items AS t1 JOIN gaming_technology.games AS t2 ON t1.game_id = t2.game_id WHERE t1.attributes ? 'mana_cost' AND (t1.attributes ->> 'mana_cost')::int > 50

[User] Filter the results to only include items from games in the 'Fantasy' genre.

[Assistant] SELECT t1.item_id, t1.item_name, t1.rarity, t2.title, t1.attributes ->> 'mana_cost' AS mana_cost FROM gaming_technology.in_game_items AS t1 JOIN gaming_technology.games AS t2 ON t1.game_id = t2.game_id WHERE t1.attributes ? 'mana_cost' AND (t1.attributes ->> 'mana_cost')::int > 50 AND t2.genre = 'Fantasy'

[User] Show me the top 5 games by number of online servers in European regions. I want the game title and the server count.

[Assistant]
SELECT g.title, COUNT(s.server_id) AS server_count
FROM gaming_technology.games g
JOIN gaming_technology.servers s ON g.game_id = s.game_id
WHERE s.region ILIKE 'eu%' AND s.status = 'online'
GROUP BY g.title
ORDER BY server_count DESC
LIMIT 5;

[User] Now include only those games whose average current_players per online server exceeds 100.

[Assistant]
SELECT g.title,
       COUNT(s.server_id) AS server_count,
       AVG(s.current_players)::numeric(10,2) AS avg_players
FROM gaming_technology.games g
JOIN gaming_technology.servers s ON g.game_id = s.game_id
WHERE s.region ILIKE 'eu%' AND s.status = 'online'
GROUP BY g.title
HAVING AVG(s.current_players) > 100
ORDER BY server_count DESC
LIMIT 5;

[User] How many players are there for each status in the players table?

[Assistant]
SELECT status, COUNT(*) AS player_count
FROM gaming_technology.players
GROUP BY status;

[User] Exclude any rows where status is NULL.

[Assistant]
SELECT status, COUNT(*) AS player_count
FROM gaming_technology.players
WHERE status IS NOT NULL
GROUP BY status;

[User] Also sort the result by player_count in descending order.

[Assistant]
SELECT status, COUNT(*) AS player_count
FROM gaming_technology.players
WHERE status IS NOT NULL
GROUP BY status
ORDER BY player_count DESC;

[User] Finally, only show statuses with more than 100 players.

[Assistant]
SELECT status, COUNT(*) AS player_count
FROM gaming_technology.players
WHERE status IS NOT NULL
GROUP BY status
HAVING COUNT(*) > 100
ORDER BY player_count DESC;

[User] List game titles and their developer names for games released in 2023 or later.

[Assistant] SELECT T1.title, T2.name FROM gaming_technology.games AS T1 JOIN gaming_technology.developers AS T2 ON T1.developer_id = T2.developer_id WHERE T1.release_date >= '2023-01-01';

[User] Also include the genre and order the results by release date descending.

[Assistant] SELECT T1.title, T2.name, T1.genre FROM gaming_technology.games AS T1 JOIN gaming_technology.developers AS T2 ON T1.developer_id = T2.developer_id WHERE T1.release_date >= '2023-01-01' ORDER BY T1.release_date DESC;

[User] List all in-game items that are either 'Rare' or 'Epic' rarity.

[Assistant] SELECT item_id, item_name, rarity FROM in_game_items WHERE rarity IN ('Rare', 'Epic');

[User] Include the item type and cost amount in the output.

[Assistant] SELECT item_id, item_name, rarity, item_type, cost_amount FROM in_game_items WHERE rarity IN ('Rare', 'Epic');

[User] Now, only show items where the cost amount is less than 500.

[Assistant] SELECT item_id, item_name, rarity, item_type, cost_amount FROM in_game_items WHERE rarity IN ('Rare', 'Epic') AND cost_amount < 500;

[User] Order the results by cost amount ascending.

[Assistant] SELECT item_id, item_name, rarity, item_type, cost_amount FROM in_game_items WHERE rarity IN ('Rare', 'Epic') AND cost_amount < 500 ORDER BY cost_amount 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 transportation.bookings ( booking_id.text, passenger_id.text, trip_id.text, seat_number.text, booking_time.timestamp, status.text, fare.numeric, payment_transaction_id.text, special_requests.text )

[User] List the number of bookings for each day.

[Assistant]
SELECT DATE(booking_time) AS booking_date, COUNT(*) AS booking_count
FROM transportation.bookings
GROUP BY DATE(booking_time);

[User] Now only include days where booking_count > 10.

[Assistant]
SELECT DATE(booking_time) AS booking_date, COUNT(*) AS booking_count
FROM transportation.bookings
GROUP BY DATE(booking_time)
HAVING COUNT(*) > 10;

[User] Also include the total fare collected for those days.

[Assistant]
SELECT DATE(booking_time) AS booking_date,
       COUNT(*) AS booking_count,
       SUM(fare) AS total_fare
FROM transportation.bookings
GROUP BY DATE(booking_time)
HAVING COUNT(*) > 10;

[User] List pairs of bookings made for the same trip, showing booking IDs and their booking_time.

[Assistant]
SELECT b1.booking_id AS booking1,
       b2.booking_id AS booking2,
       b1.trip_id,
       b1.booking_time AS time1,
       b2.booking_time AS time2
FROM transportation.bookings b1
JOIN transportation.bookings b2
  ON b1.trip_id = b2.trip_id
  AND b1.booking_id < b2.booking_id;

[User] Actually, only include pairs where the time difference between bookings is less than 2 hours.

[Assistant]
SELECT b1.booking_id AS booking1,
       b2.booking_id AS booking2,
       b1.trip_id,
       b1.booking_time AS time1,
       b2.booking_time AS time2
FROM transportation.bookings b1
JOIN transportation.bookings b2
  ON b1.trip_id = b2.trip_id
  AND b1.booking_id < b2.booking_id
WHERE ABS(EXTRACT(EPOCH FROM (b2.booking_time - b1.booking_time))) < 2 * 3600;

[User] Also calculate the difference in minutes between the two booking_time values as diff_minutes.

[Assistant]
SELECT b1.booking_id AS booking1,
       b2.booking_id AS booking2,
       b1.trip_id,
       b1.booking_time AS time1,
       b2.booking_time AS time2,
       ROUND(ABS(EXTRACT(EPOCH FROM (b2.booking_time - b1.booking_time))) / 60, 2) AS diff_minutes
FROM transportation.bookings b1
JOIN transportation.bookings b2
  ON b1.trip_id = b2.trip_id
  AND b1.booking_id < b2.booking_id
WHERE ABS(EXTRACT(EPOCH FROM (b2.booking_time - b1.booking_time))) < 2 * 3600;

[User] Find all pairs of bookings that share the same payment_transaction_id.

[Assistant]
SELECT b1.booking_id AS booking_id_1, b2.booking_id AS booking_id_2, b1.payment_transaction_id
FROM transportation.bookings b1
JOIN transportation.bookings b2
  ON b1.payment_transaction_id = b2.payment_transaction_id
 AND b1.booking_id < b2.booking_id;

[User] Now limit the results to pairs where both bookings have status 'Completed'.

[Assistant]
SELECT b1.booking_id AS booking_id_1, b2.booking_id AS booking_id_2, b1.payment_transaction_id
FROM transportation.bookings b1
JOIN transportation.bookings b2
  ON b1.payment_transaction_id = b2.payment_transaction_id
 AND b1.booking_id < b2.booking_id
WHERE b1.status = 'Completed'
  AND b2.status = 'Completed';

[User] What are the average and maximum fare amounts for each booking status?

[Assistant]
SELECT status, AVG(fare) AS avg_fare, MAX(fare) AS max_fare
FROM transportation.bookings
GROUP BY status;

[User] Only include statuses where the average fare is greater than 50.

[Assistant]
SELECT status, AVG(fare) AS avg_fare, MAX(fare) AS max_fare
FROM transportation.bookings
GROUP BY status
HAVING AVG(fare) > 50;

[User] List each booking with its previous booking time for the same passenger.

[Assistant]
SELECT b.booking_id,
       b.passenger_id,
       b.booking_time,
       LAG(b.booking_time) OVER (PARTITION BY b.passenger_id ORDER BY b.booking_time) AS previous_booking_time
FROM transportation.bookings b;

[User] I only want records where the gap between bookings is more than 7 days.

[Assistant]
SELECT booking_id,
       passenger_id,
       booking_time,
       previous_booking_time
FROM (
  SELECT booking_id,
         passenger_id,
         booking_time,
         LAG(booking_time) OVER (PARTITION BY passenger_id ORDER BY booking_time) AS previous_booking_time
  FROM transportation.bookings
) t
WHERE previous_booking_time IS NOT NULL
  AND booking_time - previous_booking_time > INTERVAL '7 days';

[User] Also include the total number of bookings for each passenger.

[Assistant]
SELECT booking_id,
       passenger_id,
       booking_time,
       previous_booking_time,
       COUNT(*) OVER (PARTITION BY passenger_id) AS total_bookings
FROM (
  SELECT booking_id,
         passenger_id,
         booking_time,
         LAG(booking_time) OVER (PARTITION BY passenger_id ORDER BY booking_time) AS previous_booking_time
  FROM transportation.bookings
) t
WHERE previous_booking_time IS NOT NULL
  AND booking_time - previous_booking_time > INTERVAL '7 days';

[User] List all booking IDs and their status for bookings that have a special request recorded.

[Assistant]
SELECT booking_id, status
FROM transportation.bookings
WHERE special_requests IS NOT NULL;

[User] Also show passenger_id and the booking_time for these bookings. Only include bookings where the special request contains the word 'meal'.

[Assistant]
SELECT booking_id, passenger_id, status, booking_time
FROM transportation.bookings
WHERE special_requests ILIKE '%meal%';

[User] Order the results by booking_time in descending order and limit the output to the 10 most recent matches.

[Assistant]
SELECT booking_id, passenger_id, status, booking_time
FROM transportation.bookings
WHERE special_requests ILIKE '%meal%'
ORDER BY booking_time 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 blockchain.blocks (
    block_id character varying(64) NOT NULL,  -- unique identifier for the block
    previous_block_id character varying(64), -- identifier of the previous block
    timestamp timestamp NOT NULL, -- time when the block was mined
    nonce integer NOT NULL, -- nonce value used in the proof of work
    merkle_root character varying(128) NOT NULL, -- root of the Merkle tree for transactions
    difficulty integer NOT NULL, -- difficulty level of the block
    PRIMARY KEY (block_id)
)

[User] Show me the average difficulty for blocks that have a previous block versus those that don't have a previous block.

[Assistant] SELECT CASE WHEN previous_block_id IS NULL THEN 'No Previous Block' ELSE 'Has Previous Block' END AS block_type, AVG(difficulty) AS avg_difficulty FROM blockchain.blocks GROUP BY block_type;

[User] Now break this down further by year, showing the yearly averages for each block type.

[Assistant] SELECT EXTRACT(YEAR FROM timestamp) AS year, CASE WHEN previous_block_id IS NULL THEN 'No Previous Block' ELSE 'Has Previous Block' END AS block_type, AVG(difficulty) AS avg_difficulty FROM blockchain.blocks GROUP BY year, block_type ORDER BY year;

[User] Can you also include the count of blocks for each year and type combination?

[Assistant] SELECT EXTRACT(YEAR FROM timestamp) AS year, CASE WHEN previous_block_id IS NULL THEN 'No Previous Block' ELSE 'Has Previous Block' END AS block_type, COUNT(*) AS block_count, AVG(difficulty) AS avg_difficulty FROM blockchain.blocks GROUP BY year, block_type ORDER BY year;

[User] Retrieve the block ID, timestamp, current block's difficulty, and the difficulty of the *previous* block for all blocks where the current block's difficulty is strictly greater than the previous block's difficulty.

[Assistant] SELECT b1.block_id, b1.timestamp, b1.difficulty AS current_difficulty, b2.difficulty AS previous_difficulty FROM blockchain.blocks b1 JOIN blockchain.blocks b2 ON b1.previous_block_id = b2.block_id WHERE b1.difficulty > b2.difficulty;

[User] Find all pairs of distinct block IDs that were mined at the exact same timestamp. Show both block IDs and the shared timestamp.

[Assistant] SELECT t1.block_id AS block_id_1, t2.block_id AS block_id_2, t1.timestamp FROM blockchain.blocks AS t1 JOIN blockchain.blocks AS t2 ON t1.timestamp = t2.timestamp WHERE t1.block_id < t2.block_id;

[User] Show me the block with the earliest timestamp and its corresponding previous block's difficulty level.

[Assistant] SELECT b1.block_id, b1.timestamp, b2.difficulty AS previous_block_difficulty FROM blockchain.blocks b1 LEFT JOIN blockchain.blocks b2 ON b1.previous_block_id = b2.block_id ORDER BY b1.timestamp ASC LIMIT 1;

[User] Now show me the same information but for the 5 earliest blocks instead of just one.

[Assistant] SELECT b1.block_id, b1.timestamp, b2.difficulty AS previous_block_difficulty FROM blockchain.blocks b1 LEFT JOIN blockchain.blocks b2 ON b1.previous_block_id = b2.block_id ORDER BY b1.timestamp ASC LIMIT 5;

[User] Find all smart contract IDs and the block IDs that were mined within 5 minutes before or after the contract deployment timestamp.

[Assistant] SELECT T1.contract_id, T2.block_id FROM blockchain.smart_contracts AS T1 JOIN blockchain.blocks AS T2 ON T2.timestamp BETWEEN T1.timestamp - INTERVAL '5 minute' AND T1.timestamp + INTERVAL '5 minute';

[User] Also include the timestamp for both the contract deployment and the block mining.

[Assistant] SELECT T1.contract_id, T1.timestamp AS contract_timestamp, T2.block_id, T2.timestamp AS block_timestamp FROM blockchain.smart_contracts AS T1 JOIN blockchain.blocks AS T2 ON T2.timestamp BETWEEN T1.timestamp - INTERVAL '5 minute' AND T1.timestamp + INTERVAL '5 minute';

[User] Filter the results to only include contracts deployed in the year 2023.

[Assistant] SELECT T1.contract_id, T1.timestamp AS contract_timestamp, T2.block_id, T2.timestamp AS block_timestamp FROM blockchain.smart_contracts AS T1 JOIN blockchain.blocks AS T2 ON T2.timestamp BETWEEN T1.timestamp - INTERVAL '5 minute' AND T1.timestamp + INTERVAL '5 minute' WHERE EXTRACT(YEAR FROM T1.timestamp) = 2023;

[User] Order the results by contract ID and then by block ID.

[Assistant] SELECT T1.contract_id, T1.timestamp AS contract_timestamp, T2.block_id, T2.timestamp AS block_timestamp FROM blockchain.smart_contracts AS T1 JOIN blockchain.blocks AS T2 ON T2.timestamp BETWEEN T1.timestamp - INTERVAL '5 minute' AND T1.timestamp + INTERVAL '5 minute' WHERE EXTRACT(YEAR FROM T1.timestamp) = 2023 ORDER BY T1.contract_id, T2.block_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 smart_money_token_inflow ( token_address.text, token_symbol.text, token_amount.numeric, usd_value.numeric, avg_price.numeric, type.numeric, address_amount.numeric, narrative.text, chain.text )

[User] What is the average USD value per address for each narrative across all chains?

[Assistant]
SELECT
  narrative,
  AVG(usd_value / NULLIF(address_amount, 0)) AS avg_usd_per_address
FROM smart_money_token_inflow
GROUP BY narrative;

[User] List the top 5 tokens by total USD inflow and outflow, including net flow, sorted by net flow descending.

[Assistant]
WITH inflow AS (
  SELECT token_symbol, chain, SUM(usd_value) AS usd_in
  FROM smart_money_token_inflow
  WHERE type = 1
  GROUP BY token_symbol, chain
),
outflow AS (
  SELECT token_symbol, chain, SUM(usd_value) AS usd_out
  FROM smart_money_token_inflow
  WHERE type = 2
  GROUP BY token_symbol, chain
),
net_flow AS (
  SELECT
    i.token_symbol,
    i.chain,
    COALESCE(i.usd_in, 0) AS usd_in,
    COALESCE(o.usd_out, 0) AS usd_out,
    COALESCE(i.usd_in, 0) - COALESCE(o.usd_out, 0) AS net_flow
  FROM inflow i
  LEFT JOIN outflow o
    ON i.token_symbol = o.token_symbol
   AND i.chain = o.chain
)
SELECT token_symbol, chain, usd_in, usd_out, net_flow
FROM net_flow
ORDER BY net_flow DESC
LIMIT 5;

[User] Now filter the results to only include tokens where net flow is positive.

[Assistant]
WITH inflow AS (
  SELECT token_symbol, chain, SUM(usd_value) AS usd_in
  FROM smart_money_token_inflow
  WHERE type = 1
  GROUP BY token_symbol, chain
),
outflow AS (
  SELECT token_symbol, chain, SUM(usd_value) AS usd_out
  FROM smart_money_token_inflow
  WHERE type = 2
  GROUP BY token_symbol, chain
),
net_flow AS (
  SELECT
    i.token_symbol,
    i.chain,
    COALESCE(i.usd_in, 0) AS usd_in,
    COALESCE(o.usd_out, 0) AS usd_out,
    COALESCE(i.usd_in, 0) - COALESCE(o.usd_out, 0) AS net_flow
  FROM inflow i
  LEFT JOIN outflow o
    ON i.token_symbol = o.token_symbol
   AND i.chain = o.chain
)
SELECT token_symbol, chain, usd_in, usd_out, net_flow
FROM net_flow
WHERE net_flow > 0
ORDER BY net_flow DESC
LIMIT 5;

[User] For each chain, find the token with the highest net USD inflow (buys minus sells). Show token_symbol, chain, and net_inflow.

[Assistant]
WITH inflow AS (
  SELECT token_symbol, chain, SUM(usd_value) AS usd_in
  FROM smart_money_token_inflow
  WHERE type = 1
  GROUP BY token_symbol, chain
),
outflow AS (
  SELECT token_symbol, chain, SUM(usd_value) AS usd_out
  FROM smart_money_token_inflow
  WHERE type = 2
  GROUP BY token_symbol, chain
),
net AS (
  SELECT
    COALESCE(i.token_symbol, o.token_symbol) AS token_symbol,
    COALESCE(i.chain, o.chain) AS chain,
    COALESCE(i.usd_in, 0) - COALESCE(o.usd_out, 0) AS net_inflow
  FROM inflow i
  FULL JOIN outflow o
    ON i.token_symbol = o.token_symbol
   AND i.chain = o.chain
)
SELECT token_symbol, chain, net_inflow
FROM (
  SELECT
    token_symbol,
    chain,
    net_inflow,
    ROW_NUMBER() OVER (PARTITION BY chain ORDER BY net_inflow DESC) AS rn
  FROM net
) sub
WHERE rn = 1;

[User] Only include tokens that were involved in at least 10 distinct addresses for buy transactions.

[Assistant]
WITH inflow AS (
  SELECT token_symbol, chain, SUM(usd_value) AS usd_in, SUM(address_amount) AS addr_count
  FROM smart_money_token_inflow
  WHERE type = 1
  GROUP BY token_symbol, chain
),
outflow AS (
  SELECT token_symbol, chain, SUM(usd_value) AS usd_out
  FROM smart_money_token_inflow
  WHERE type = 2
  GROUP BY token_symbol, chain
),
net AS (
  SELECT
    i.token_symbol,
    i.chain,
    i.usd_in - COALESCE(o.usd_out, 0) AS net_inflow,
    i.addr_count
  FROM inflow i
  LEFT JOIN outflow o
    ON i.token_symbol = o.token_symbol
   AND i.chain = o.chain
)
SELECT token_symbol, chain, net_inflow
FROM (
  SELECT
    token_symbol,
    chain,
    net_inflow,
    addr_count,
    ROW_NUMBER() OVER (PARTITION BY chain ORDER BY net_inflow DESC) AS rn
  FROM net
) sub
WHERE rn = 1
  AND addr_count >= 10;

[User] List tokens with net outflow (type=2) on the 'Ethereum' chain. Show token_symbol and total usd_value sold.

[Assistant]
SELECT token_symbol, SUM(usd_value) AS total_sold
FROM smart_money_token_inflow
WHERE type = 2 AND chain = 'Ethereum'
GROUP BY token_symbol;

[User] Now limit to tokens with total_sold above 10000 and order by total_sold descending.

[Assistant]
SELECT token_symbol, SUM(usd_value) AS total_sold
FROM smart_money_token_inflow
WHERE type = 2 AND chain = 'Ethereum'
GROUP BY token_symbol
HAVING SUM(usd_value) > 10000
ORDER BY total_sold DESC;

[User] Which chain has the highest total USD inflow from buy transactions (type=1), and how many distinct tokens were involved in that inflow?

[Assistant]
SELECT chain, SUM(usd_value) AS total_inflow, COUNT(DISTINCT token_symbol) AS distinct_tokens
FROM smart_money_token_inflow
WHERE type = 1
GROUP BY chain
ORDER BY total_inflow DESC
LIMIT 1;

[User] I also want to see the average price at which those tokens were bought for that chain.

[Assistant]
WITH inflow AS (
  SELECT chain, SUM(usd_value) AS total_inflow
  FROM smart_money_token_inflow
  WHERE type = 1
  GROUP BY chain
), top_chain AS (
  SELECT chain FROM inflow ORDER BY total_inflow DESC LIMIT 1
)
SELECT i.chain, AVG(i.avg_price) AS avg_buy_price
FROM smart_money_token_inflow i
JOIN top_chain t ON i.chain = t.chain
WHERE i.type = 1;

[User] Actually, filter to narratives where the total USD inflow is above 50000.

[Assistant]
SELECT narrative, SUM(usd_value) AS total_inflow, COUNT(DISTINCT token_symbol) AS distinct_tokens
FROM smart_money_token_inflow
WHERE type = 1
GROUP BY narrative
HAVING SUM(usd_value) > 50000;

[User] Please order the results by average price descending and show the top 2 chains.

[Assistant]
SELECT chain, SUM(usd_value) AS total_inflow, COUNT(DISTINCT token_symbol) AS distinct_tokens, AVG(avg_price) AS avg_buy_price
FROM smart_money_token_inflow
WHERE type = 1
GROUP BY chain
ORDER BY avg_buy_price DESC
LIMIT 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 trading_platform.assets (
    asset_id character varying(64) NOT NULL,  -- unique identifier for the asset
    name character varying(128) NOT NULL, -- name of the asset
    symbol character varying(32) NOT NULL, -- symbol of the asset
    type character varying(32) NOT NULL, -- type of the asset (e.g., cryptocurrency, stock)
    PRIMARY KEY (asset_id)
)
CREATE TABLE trading_platform.dapps ( dapp_id.text, name.text, description.text, url.text )

[User] Give me the list of DApp names and URLs whose description contains any asset symbol from the assets table.

[Assistant]
SELECT DISTINCT d.name, d.url
FROM trading_platform.dapps d
JOIN trading_platform.assets a ON d.description ILIKE '%' || a.symbol || '%';

[User] Could you also add the matching asset symbol in the result?

[Assistant]
SELECT DISTINCT d.name AS dapp_name, d.url, a.symbol AS asset_symbol
FROM trading_platform.dapps d
JOIN trading_platform.assets a ON d.description ILIKE '%' || a.symbol || '%';

[User] Show only those DApps where the description contains more than one different asset symbol.

[Assistant]
SELECT d.name AS dapp_name, d.url, COUNT(DISTINCT a.symbol) AS asset_symbol_count
FROM trading_platform.dapps d
JOIN trading_platform.assets a ON d.description ILIKE '%' || a.symbol || '%'
GROUP BY d.name, d.url
HAVING COUNT(DISTINCT a.symbol) > 1;

[User] Now show for each such DApp: its name, URL, and the comma-separated list of matching asset symbols.

[Assistant]
SELECT d.name AS dapp_name, d.url, STRING_AGG(DISTINCT a.symbol, ', ') AS asset_symbols
FROM trading_platform.dapps d
JOIN trading_platform.assets a ON d.description ILIKE '%' || a.symbol || '%'
GROUP BY d.name, d.url
HAVING COUNT(DISTINCT a.symbol) > 1;

[User] Show the names, symbols, and types of all assets whose symbol starts with the letter 'B'.

[Assistant]
SELECT name, symbol, type
FROM trading_platform.assets
WHERE symbol LIKE 'B%';

[User] How many distinct IP addresses have ever connected as peers on the platform?

[Assistant]
SELECT COUNT(DISTINCT ip_address) AS distinct_ip_count
FROM trading_platform.peers;

[User] Show the total number of notifications sent per user.

[Assistant]
SELECT user_id, COUNT(*) AS total_notifications
FROM trading_platform.notifications
GROUP BY user_id;

[User] I only want to see users who have received at least 3 notifications, and include the date of their most recent notification.

[Assistant]
SELECT user_id, COUNT(*) AS total_notifications, MAX(sent_at) AS latest_notification
FROM trading_platform.notifications
GROUP BY user_id
HAVING COUNT(*) >= 3;

[User] Instead, please show only those users who have at least 3 unread notifications and sort by number of unread notifications descending.

[Assistant]
SELECT user_id, COUNT(*) AS unread_notifications, MAX(sent_at) AS latest_unread
FROM trading_platform.notifications
WHERE read_at IS NULL
GROUP BY user_id
HAVING COUNT(*) >= 3
ORDER BY unread_notifications DESC;

[User] Show only the top 2 users by unread notifications.

[Assistant]
SELECT user_id, COUNT(*) AS unread_notifications, MAX(sent_at) AS latest_unread
FROM trading_platform.notifications
WHERE read_at IS NULL
GROUP BY user_id
HAVING COUNT(*) >= 3
ORDER BY unread_notifications DESC
LIMIT 2;

[User] List all asset symbols where the asset type is 'token'.

[Assistant] SELECT symbol FROM trading_platform.assets WHERE type = 'token';

[User] Show the names and types of all assets whose symbol is exactly 3 characters long.

[Assistant] SELECT name, type, symbol FROM trading_platform.assets WHERE LENGTH(symbol) = 3;

[User] Also, I want to order the results alphabetically by asset name.

[Assistant] SELECT name, type, symbol FROM trading_platform.assets WHERE LENGTH(symbol) = 3 ORDER BY name ASC;

[User] Actually, can you only show assets of type 'token' in the result?

[Assistant] SELECT name, type, symbol FROM trading_platform.assets WHERE LENGTH(symbol) = 3 AND type = 'token' ORDER BY name ASC;

[User] Now, just return the asset name and symbol for these tokens, sorted by symbol descending.

[Assistant] SELECT name, symbol FROM trading_platform.assets WHERE LENGTH(symbol) = 3 AND type = 'token' ORDER BY symbol 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 hospitality_technology.guests ( guest_id text PRIMARY KEY, first_name text, last_name text, email text, phone_number text, date_of_birth date, address_line1 text, city text, state_province text, postal_code text, country_code text, preferences text, loyalty_member_id text, communication_consent boolean, created_at timestamp, updated_at timestamp )

[User] Retrieve the first name, last name, and email for all guests.

[Assistant] SELECT first_name, last_name, email FROM hospitality_technology.guests;

[User] Can you also include their loyalty member ID and whether they have given communication consent?

[Assistant] SELECT first_name, last_name, email, loyalty_member_id, communication_consent FROM hospitality_technology.guests;

[User] Filter this list to only include guests who have a loyalty member ID, have consented to communication, and were created in 2023. Order the results by their last name.

[Assistant] SELECT first_name, last_name, email, loyalty_member_id, communication_consent FROM hospitality_technology.guests WHERE loyalty_member_id IS NOT NULL AND communication_consent = TRUE AND created_at >= '2023-01-01' AND created_at < '2024-01-01' ORDER BY last_name;

[User] List all guests who have provided a phone number, showing their guest ID and phone number.

[Assistant] SELECT guest_id, phone_number FROM hospitality_technology.guests WHERE phone_number IS NOT NULL AND phone_number <> '';

[User] Can you also include their email addresses in the result?

[Assistant] SELECT guest_id, phone_number, email FROM hospitality_technology.guests WHERE phone_number IS NOT NULL AND phone_number <> '';

[User] Show me all guests from 'CA' along with their full name and email address.

[Assistant] SELECT guest_id, CONCAT(first_name, ' ', last_name) AS full_name, email FROM hospitality_technology.guests WHERE country_code = 'CA';

[User] Show me the list of guests who were created in 2024, along with their first and last names and registration date.

[Assistant] SELECT guest_id, first_name, last_name, created_at FROM hospitality_technology.guests WHERE EXTRACT(YEAR FROM created_at) = 2024;

[User] Please filter this list to include only those who have a loyalty member ID.

[Assistant] SELECT guest_id, first_name, last_name, created_at FROM hospitality_technology.guests WHERE EXTRACT(YEAR FROM created_at) = 2024 AND loyalty_member_id IS NOT NULL AND loyalty_member_id <> '';

[User] Also show their email and date of birth.

[Assistant] SELECT guest_id, first_name, last_name, email, date_of_birth, created_at FROM hospitality_technology.guests WHERE EXTRACT(YEAR FROM created_at) = 2024 AND loyalty_member_id IS NOT NULL AND loyalty_member_id <> '';

[User] How many guests are there in each city? Show the city and the guest count.

[Assistant] SELECT city, COUNT(guest_id) FROM hospitality_technology.guests GROUP BY city;

[User] Please only show cities with more than 10 guests and order by count descending.

[Assistant] SELECT city, COUNT(guest_id) FROM hospitality_technology.guests GROUP BY city HAVING COUNT(guest_id) > 10 ORDER BY COUNT(guest_id) DESC;

[User] List the first and last names of guests residing in California who are loyalty members.

[Assistant] SELECT first_name, last_name FROM hospitality_technology.guests WHERE state_province = 'California' AND loyalty_member_id IS NOT NULL;

[User] Now, only include those who have communication consent enabled and sort by last name.

[Assistant] SELECT first_name, last_name FROM hospitality_technology.guests WHERE state_province = 'California' AND loyalty_member_id IS NOT NULL AND communication_consent = TRUE ORDER BY last_name;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE legal_services.time_entries ( entry_id text PRIMARY KEY, case_id text, lawyer_id text, date_worked date, hours_spent numeric, billing_rate numeric, description text, is_billable bool, is_billed bool, invoice_id text, created_at timestamp )

[User] List all time entries that do not have a description, including the entry ID, date worked, hours spent, and the first and last name of the lawyer who recorded the entry.

[Assistant] SELECT te.entry_id, te.date_worked, te.hours_spent, l.first_name, l.last_name FROM legal_services.time_entries AS te JOIN legal_services.lawyers AS l ON te.lawyer_id = l.lawyer_id WHERE te.description IS NULL OR te.description = '';

[User] Show me the total hours spent by each lawyer on a specific case, say with case_id = 'CASE001'.

[Assistant] SELECT lawyer_id, SUM(hours_spent) AS total_hours FROM legal_services.time_entries WHERE case_id = 'CASE001' GROUP BY lawyer_id;

[User] Can you also include only the entries that are billable?

[Assistant] SELECT lawyer_id, SUM(hours_spent) AS total_hours FROM legal_services.time_entries WHERE case_id = 'CASE001' AND is_billable = TRUE GROUP BY lawyer_id;

[User] Now, show only those lawyers who have logged more than 5 billable hours on this case.

[Assistant] SELECT lawyer_id, SUM(hours_spent) AS total_hours FROM legal_services.time_entries WHERE case_id = 'CASE001' AND is_billable = TRUE GROUP BY lawyer_id HAVING SUM(hours_spent) > 5;

[User] How many time entries were recorded on each date? List the date and the count of entries for that date, ordered by date.

[Assistant] SELECT date_worked, COUNT(*) AS entry_count FROM legal_services.time_entries GROUP BY date_worked ORDER BY date_worked;

[User] List each case_id along with the total hours worked and total billed amount for that case.

[Assistant] SELECT case_id, SUM(hours_spent) AS total_hours, SUM(hours_spent * billing_rate) AS total_billed_amount FROM legal_services.time_entries GROUP BY case_id;

[User] Only include entries that have been billed.

[Assistant] SELECT case_id, SUM(hours_spent) AS total_hours, SUM(hours_spent * billing_rate) AS total_billed_amount FROM legal_services.time_entries WHERE is_billed = TRUE GROUP BY case_id;

[User] And restrict to cases worked on in February 2024 only.

[Assistant] SELECT case_id, SUM(hours_spent) AS total_hours, SUM(hours_spent * billing_rate) AS total_billed_amount FROM legal_services.time_entries WHERE is_billed = TRUE AND date_worked >= '2024-02-01' AND date_worked < '2024-03-01' GROUP BY case_id;

[User] Please order the results by total_billed_amount descending.

[Assistant] SELECT case_id, SUM(hours_spent) AS total_hours, SUM(hours_spent * billing_rate) AS total_billed_amount FROM legal_services.time_entries WHERE is_billed = TRUE AND date_worked >= '2024-02-01' AND date_worked < '2024-03-01' GROUP BY case_id ORDER BY total_billed_amount DESC;

[User] Show me all time entries for case ID 'case_abc', including the entry ID, date worked, hours spent, and the first and last name of the lawyer.

[Assistant] SELECT te.entry_id, te.date_worked, te.hours_spent, l.first_name, l.last_name FROM legal_services.time_entries AS te JOIN legal_services.lawyers AS l ON te.lawyer_id = l.lawyer_id WHERE te.case_id = 'case_abc';

[User] Okay, now only show the entries that are marked as billable.

[Assistant] SELECT te.entry_id, te.date_worked, te.hours_spent, l.first_name, l.last_name FROM legal_services.time_entries AS te JOIN legal_services.lawyers AS l ON te.lawyer_id = l.lawyer_id WHERE te.case_id = 'case_abc' AND te.is_billable = TRUE;

[User] Also, include the description for these entries and sort them by date worked, oldest first.

[Assistant] SELECT te.entry_id, te.date_worked, te.hours_spent, l.first_name, l.last_name, te.description FROM legal_services.time_entries AS te JOIN legal_services.lawyers AS l ON te.lawyer_id = l.lawyer_id WHERE te.case_id = 'case_abc' AND te.is_billable = TRUE ORDER BY te.date_worked ASC;

[User] Show the invoice_id and total hours logged for each invoice.

[Assistant] SELECT invoice_id, SUM(hours_spent) AS total_hours FROM legal_services.time_entries WHERE invoice_id IS NOT NULL GROUP BY invoice_id;

[User] Only include invoices with more than 10 total hours.

[Assistant] SELECT invoice_id, SUM(hours_spent) AS total_hours FROM legal_services.time_entries WHERE invoice_id IS NOT NULL GROUP BY invoice_id HAVING SUM(hours_spent) > 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 transportation.trips ( trip_id text PRIMARY KEY, route_id text, vehicle_id text, driver_id text, scheduled_departure timestamp, actual_departure timestamp, scheduled_arrival timestamp, actual_arrival timestamp, origin_location_id text, destination_location_id text, status text, passenger_count int, cargo_manifest_id text )

[User] Give me all trips where the trip status is 'Completed' with their trip ID, vehicle ID, and number of passengers.

[Assistant] SELECT trip_id, vehicle_id, passenger_count FROM transportation.trips WHERE status = 'Completed';

[User] Now, also include the scheduled and actual arrival times.

[Assistant] SELECT trip_id, vehicle_id, passenger_count, scheduled_arrival, actual_arrival FROM transportation.trips WHERE status = 'Completed';

[User] I want to filter out trips that had zero passengers.

[Assistant] SELECT trip_id, vehicle_id, passenger_count, scheduled_arrival, actual_arrival FROM transportation.trips WHERE status = 'Completed' AND passenger_count > 0;

[User] Actually, can you also include the driver ID in the output?

[Assistant] SELECT trip_id, vehicle_id, driver_id, passenger_count, scheduled_arrival, actual_arrival FROM transportation.trips WHERE status = 'Completed' AND passenger_count > 0;

[User] List all trips along with their trip ID and the number of passengers if the trip is currently in progress.

[Assistant] SELECT trip_id, passenger_count FROM transportation.trips WHERE status = 'In Progress';

[User] Add the vehicle_id and driver_id to the result as well.

[Assistant] SELECT trip_id, passenger_count, vehicle_id, driver_id FROM transportation.trips WHERE status = 'In Progress';

[User] Actually, I also need the scheduled departure time for these trips.

[Assistant] SELECT trip_id, passenger_count, vehicle_id, driver_id, scheduled_departure FROM transportation.trips WHERE status = 'In Progress';

[User] Sort the result by scheduled departure in ascending order.

[Assistant] SELECT trip_id, passenger_count, vehicle_id, driver_id, scheduled_departure FROM transportation.trips WHERE status = 'In Progress' ORDER BY scheduled_departure ASC;

[User] Show all trips with their trip ID, route ID, the ID of their origin location, and the ID of their destination location, where the route ID starts with 'EX'.

[Assistant] SELECT trip_id, route_id, origin_location_id, destination_location_id FROM transportation.trips WHERE route_id LIKE 'EX%';

[User] For each pair of origin and destination location IDs, show the number of completed trips between them.

[Assistant] SELECT origin_location_id, destination_location_id, COUNT(*) AS completed_trip_count FROM transportation.trips WHERE status = 'Completed' GROUP BY origin_location_id, destination_location_id;

[User] List all trips where the origin location is different from the destination location and show the trip ID, origin location ID, destination location ID, and route ID.

[Assistant] SELECT trip_id, origin_location_id, destination_location_id, route_id FROM transportation.trips WHERE origin_location_id <> destination_location_id;

[User] For each origin and destination location pair, provide the total number of trips along with the average actual_arrival time.

[Assistant] SELECT origin_location_id, destination_location_id, COUNT(*) AS trip_count, AVG(EXTRACT(EPOCH FROM actual_arrival)) AS avg_actual_arrival_epoch FROM transportation.trips GROUP BY origin_location_id, destination_location_id;

[User] Can you also filter this to only include pairs where the trip count is greater than 3?

[Assistant] SELECT origin_location_id, destination_location_id, COUNT(*) AS trip_count, AVG(EXTRACT(EPOCH FROM actual_arrival)) AS avg_actual_arrival_epoch FROM transportation.trips GROUP BY origin_location_id, destination_location_id HAVING COUNT(*) > 3;

[User] Instead of the epoch average, show the average difference (in minutes) between scheduled_arrival and actual_arrival for these pairs.

[Assistant] SELECT origin_location_id, destination_location_id, COUNT(*) AS trip_count, AVG(EXTRACT(EPOCH FROM actual_arrival - scheduled_arrival)/60.0) AS avg_delay_minutes FROM transportation.trips GROUP BY origin_location_id, destination_location_id HAVING COUNT(*) > 3;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE insurance.claims (
    claim_id character varying(64) NOT NULL, -- unique identifier for the claim
    policy_id character varying(64) NOT NULL, -- identifier of the policy under which the claim is made (FK to policies)
    customer_id character varying(64) NOT NULL, -- identifier of the customer making the claim (FK to customers)
    incident_date timestamp NOT NULL, -- date and time of the incident leading to the claim
    reported_date timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, -- date the claim was reported
    description text NOT NULL, -- detailed description of the incident and claim
    estimated_loss numeric(15, 2), -- initial estimated cost of the loss
    status character varying(30) NOT NULL, -- e.g., Filed, Processing, Under Review, Approved, Denied, Settled
    settlement_amount numeric(15, 2), -- final amount paid out
    settlement_date date,
    claim_handler_id character varying(64), -- identifier for the employee handling the claim (FK to employees/adjusters)
    police_report_number character varying(100),
    PRIMARY KEY (claim_id)
)

[User] Show the number of claims filed for each distinct status, ordered by the count in descending order.

[Assistant]
SELECT status, COUNT(*) AS claim_count
FROM insurance.claims
GROUP BY status
ORDER BY claim_count DESC;

[User] List each claim_handler_id along with the number of claims they've handled and the total settlement_amount they've paid out.

[Assistant]
SELECT claim_handler_id,
       COUNT(*) AS total_claims,
       SUM(settlement_amount) AS total_settlement
FROM insurance.claims
GROUP BY claim_handler_id;

[User] In addition, include the claim_id of the single claim with the highest settlement_amount for each handler.

[Assistant]
SELECT ag.claim_handler_id,
       ag.total_claims,
       ag.total_settlement,
       c_max.claim_id               AS max_settlement_claim_id,
       c_max.settlement_amount      AS max_settlement_amount
FROM (
  SELECT claim_handler_id,
         COUNT(*) AS total_claims,
         SUM(settlement_amount) AS total_settlement
  FROM insurance.claims
  GROUP BY claim_handler_id
) ag
JOIN insurance.claims c_max
  ON c_max.claim_handler_id = ag.claim_handler_id
  AND c_max.settlement_amount = (
    SELECT MAX(settlement_amount)
    FROM insurance.claims
    WHERE claim_handler_id = ag.claim_handler_id
  );

[User] Only include handlers who have managed at least 3 claims and have a non-null claim_handler_id.

[Assistant]
SELECT ag.claim_handler_id,
       ag.total_claims,
       ag.total_settlement,
       c_max.claim_id               AS max_settlement_claim_id,
       c_max.settlement_amount      AS max_settlement_amount
FROM (
  SELECT claim_handler_id,
         COUNT(*) AS total_claims,
         SUM(settlement_amount) AS total_settlement
  FROM insurance.claims
  GROUP BY claim_handler_id
  HAVING COUNT(*) >= 3
     AND claim_handler_id IS NOT NULL
) ag
JOIN insurance.claims c_max
  ON c_max.claim_handler_id = ag.claim_handler_id
  AND c_max.settlement_amount = (
    SELECT MAX(settlement_amount)
    FROM insurance.claims
    WHERE claim_handler_id = ag.claim_handler_id
  );

[User] Finally, sort the results by total_settlement in descending order.

[Assistant]
SELECT ag.claim_handler_id,
       ag.total_claims,
       ag.total_settlement,
       c_max.claim_id               AS max_settlement_claim_id,
       c_max.settlement_amount      AS max_settlement_amount
FROM (
  SELECT claim_handler_id,
         COUNT(*) AS total_claims,
         SUM(settlement_amount) AS total_settlement
  FROM insurance.claims
  GROUP BY claim_handler_id
  HAVING COUNT(*) >= 3
     AND claim_handler_id IS NOT NULL
) ag
JOIN insurance.claims c_max
  ON c_max.claim_handler_id = ag.claim_handler_id
  AND c_max.settlement_amount = (
    SELECT MAX(settlement_amount)
    FROM insurance.claims
    WHERE claim_handler_id = ag.claim_handler_id
  )
ORDER BY ag.total_settlement DESC;

[User] Calculate the average number of days between when an incident occurred and when the claim was reported, but only for claims that were settled in the year 2023.

[Assistant]
SELECT
  AVG(EXTRACT(EPOCH FROM (reported_date - incident_date)) / 86400.0)::numeric(10, 2)
FROM
  insurance.claims
WHERE
  settlement_date IS NOT NULL AND EXTRACT(YEAR FROM settlement_date) = 2023;

[User] What is the average estimated_loss for claims with status 'Filed' or 'Approved'?

[Assistant]
SELECT AVG(estimated_loss) AS avg_estimated_loss
FROM insurance.claims
WHERE status IN ('Filed', 'Approved');

[User] List the claim ID, policy ID, reported date, and settlement date for claims that have been processed by a claim handler.

[Assistant]
SELECT claim_id, policy_id, reported_date, settlement_date
FROM insurance.claims
WHERE claim_handler_id IS NOT NULL;

[User] Actually, only show claims where the settlement date is not null as well.

[Assistant]
SELECT claim_id, policy_id, reported_date, settlement_date
FROM insurance.claims
WHERE claim_handler_id IS NOT NULL AND settlement_date IS NOT NULL;

[User] Now, filter to only include claims settled after January 1, 2024.

[Assistant]
SELECT claim_id, policy_id, reported_date, settlement_date
FROM insurance.claims
WHERE claim_handler_id IS NOT NULL AND settlement_date IS NOT NULL
  AND settlement_date > '2024-01-01';

[User] Also, add a column showing the number of days between the reported date and the settlement date, and sort results by that column in descending order.

[Assistant]
SELECT claim_id, policy_id, reported_date, settlement_date,
       (settlement_date - reported_date::date) AS days_to_settle
FROM insurance.claims
WHERE claim_handler_id IS NOT NULL AND settlement_date IS NOT NULL
  AND settlement_date > '2024-01-01'
ORDER BY days_to_settle DESC;

[User] How many agents are currently active in each license state?

[Assistant]
SELECT license_state, COUNT(*) AS active_agent_count
FROM insurance.agents
WHERE status = 'Active'
GROUP BY license_state;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE government_services.citizens ( citizen_id text, national_id_number text, first_name text, last_name text, date_of_birth date, gender text, primary_address text, contact_email text, contact_phone text, registration_date timestamp, is_verified boolean )
CREATE TABLE government_services.agencies ( agency_id character varying(64) NOT NULL, agency_name character varying(255) NOT NULL, jurisdiction_level character varying(50) NOT NULL, primary_contact_email character varying(128), main_phone_number character varying(32), website_url character varying(255), established_date date, parent_agency_id character varying(64), PRIMARY KEY (agency_id) )
CREATE TABLE government_services.payments ( payment_id text PRIMARY KEY, application_id text, citizen_id text, service_id text, amount numeric, currency text, payment_method text, payment_provider_reference text, payment_timestamp timestamp, status text, notes text )
CREATE TABLE government_services.employees (
    employee_id character varying(64) NOT NULL, -- unique identifier for the government employee
    agency_id character varying(64) NOT NULL, -- FK to agencies table
    first_name character varying(100) NOT NULL,
    last_name character varying(100) NOT NULL,
    job_title character varying(150) NOT NULL,
    department character varying(100),
    work_email character varying(128) NOT NULL UNIQUE,
    work_phone character varying(32),
    hire_date date NOT NULL,
    termination_date date, -- null if currently employed
    access_level character varying(50), -- Role or permission level
    manager_employee_id character varying(64), -- FK to self for reporting structure
    PRIMARY KEY (employee_id)
)
CREATE TABLE government_services.service_locations ( location_id text PRIMARY KEY, agency_id text, location_name text, address text, city text, state text, postal_code text, latitude numeric, longitude numeric, operating_hours text, contact_phone text, is_accessible boolean )
CREATE TABLE government_services.appointments ( appointment_id character varying(64) NOT NULL, citizen_id character varying(64) NOT NULL, employee_id character varying(64), location_id character varying(64), service_id character varying(64), scheduled_start_time timestamp NOT NULL, scheduled_end_time timestamp, purpose text NOT NULL, status character varying(30) NOT NULL, booking_method character varying(50), created_at timestamp NOT NULL, notes text, PRIMARY KEY (appointment_id) )
CREATE TABLE government_services.notifications ( notification_id character varying(64) NOT NULL, citizen_id character varying(64) NOT NULL, application_id character varying(64), message_subject character varying(255), message_body text NOT NULL, channel character varying(30) NOT NULL, sent_at timestamp NOT NULL, status character varying(30) NOT NULL, related_entity_type character varying(50), related_entity_id character varying(64), PRIMARY KEY (notification_id) )

[User] Find all top-level agencies that do not have a parent agency. Display their agency_id and agency_name.

[Assistant]
SELECT agency_id, agency_name
FROM government_services.agencies
WHERE parent_agency_id IS NULL;

[User] Find currently employed employees whose direct manager has been terminated. Display the employee's full name, hire date, manager's full name, and manager's termination date.

[Assistant]
SELECT e.employee_id,
       CONCAT(e.first_name, ' ', e.last_name) AS employee_full_name,
       e.hire_date,
       CONCAT(m.first_name, ' ', m.last_name) AS manager_full_name,
       m.termination_date
FROM government_services.employees e
JOIN government_services.employees m ON e.manager_employee_id = m.employee_id
WHERE e.termination_date IS NULL
  AND m.termination_date IS NOT NULL;

[User] For all appointments scheduled after '2024-07-01', list the appointment ID, the full name of the citizen, the location name, and the city.

[Assistant]
SELECT a.appointment_id,
       CONCAT(c.first_name, ' ', c.last_name) AS citizen_full_name,
       l.location_name,
       l.city
FROM government_services.appointments a
JOIN government_services.citizens c ON a.citizen_id = c.citizen_id
JOIN government_services.service_locations l ON a.location_id = l.location_id
WHERE a.scheduled_start_time > '2024-07-01';

[User] List the full name of employees and the names of the agencies they work for, but only for employees who are currently employed.

[Assistant]
SELECT e.first_name || ' ' || e.last_name AS employee_full_name, a.agency_name
FROM government_services.employees e
JOIN government_services.agencies a ON e.agency_id = a.agency_id
WHERE e.termination_date IS NULL;

[User] Show the payment ID, amount, and payment method for all payments made in USD with an amount greater than 50.

[Assistant]
SELECT payment_id, amount, payment_method
FROM government_services.payments
WHERE currency = 'USD' AND amount > 50;

[User] For each service, show the service name and the total number of applications submitted for it.

[Assistant]
SELECT s.service_name, COUNT(a.application_id) AS total_applications
FROM government_services.services s
LEFT JOIN government_services.applications a ON s.service_id = a.service_id
GROUP BY s.service_name;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE transportation.routes ( route_id text PRIMARY KEY, route_number text, description text, origin_location_id text, destination_location_id text, distance_km numeric, estimated_duration_minutes int, type text )
CREATE TABLE transportation.maintenance_logs ( log_id.text, vehicle_id.text, service_date.date, odometer_reading.integer, service_type.text, description.text, cost.numeric, mechanic_name.text, next_service_due_date.date )
CREATE TABLE transportation.fuel_logs ( fuel_log_id text, vehicle_id text, trip_id text, log_timestamp timestamp, fuel_type text, quantity numeric, unit text, cost_per_unit numeric, total_cost numeric, odometer_reading integer, location_id text )
CREATE TABLE transportation.passengers ( passenger_id text, first_name text, last_name text, email text, phone_number text, date_of_birth date, loyalty_program_id text, created_at timestamp )

[User] Show me the first name, last name, and email address for all passengers who are part of the loyalty program with ID 'Gold'.

[Assistant] SELECT first_name ,  last_name ,  email FROM transportation.passengers WHERE loyalty_program_id  =  'Gold'

[User] Now, narrow this list to only include those passengers whose record was created after January 1, 2023.

[Assistant] SELECT first_name ,  last_name ,  email FROM transportation.passengers WHERE loyalty_program_id  =  'Gold' AND created_at  >  '2023-01-01'

[User] For each vehicle that appears in both the maintenance logs and fuel logs tables, calculate the total maintenance cost and the total fuel cost. Display the vehicle ID and these two total costs.

[Assistant] SELECT T1.vehicle_id ,  SUM(T1.cost) AS total_maintenance_cost ,  SUM(T2.total_cost) AS total_fuel_cost FROM transportation.maintenance_logs AS T1 JOIN transportation.fuel_logs AS T2 ON T1.vehicle_id  =  T2.vehicle_id GROUP BY T1.vehicle_id

[User] Now, only include vehicles where the total maintenance cost exceeds 5000.

[Assistant] SELECT T1.vehicle_id ,  SUM(T1.cost) AS total_maintenance_cost ,  SUM(T2.total_cost) AS total_fuel_cost FROM transportation.maintenance_logs AS T1 JOIN transportation.fuel_logs AS T2 ON T1.vehicle_id  =  T2.vehicle_id GROUP BY T1.vehicle_id HAVING SUM(T1.cost)  >  5000

[User] Also, only consider fuel log entries from the year 2023 for the fuel cost calculation.

[Assistant] SELECT T1.vehicle_id ,  SUM(T1.cost) AS total_maintenance_cost ,  SUM(CASE WHEN STRFTIME('%Y', T2.log_timestamp) = '2023' THEN T2.total_cost ELSE 0 END) AS total_fuel_cost FROM transportation.maintenance_logs AS T1 JOIN transportation.fuel_logs AS T2 ON T1.vehicle_id  =  T2.vehicle_id GROUP BY T1.vehicle_id HAVING SUM(T1.cost)  >  5000

[User] Show the total number of maintenance logs for each vehicle along with the vehicle's make and model.

[Assistant]
SELECT v.vehicle_id, v.make, v.model, COUNT(m.log_id) AS maintenance_count
FROM transportation.vehicles v
LEFT JOIN transportation.maintenance_logs m ON v.vehicle_id = m.vehicle_id
GROUP BY v.vehicle_id, v.make, v.model;

[User] List all bookings with the first and last name of the passenger and trip_id.

[Assistant]
SELECT b.booking_id, b.trip_id, p.first_name, p.last_name
FROM transportation.bookings b
JOIN transportation.passengers p ON b.passenger_id = p.passenger_id;

[User] Add the date when the booking was made and the booking status.

[Assistant]
SELECT b.booking_id, b.trip_id, p.first_name, p.last_name, b.booking_time, b.status
FROM transportation.bookings b
JOIN transportation.passengers p ON b.passenger_id = p.passenger_id;

[User] Filter to only show bookings where the status is either 'Pending' or 'Confirmed'.

[Assistant]
SELECT b.booking_id, b.trip_id, p.first_name, p.last_name, b.booking_time, b.status
FROM transportation.bookings b
JOIN transportation.passengers p ON b.passenger_id = p.passenger_id
WHERE b.status IN ('Pending', 'Confirmed');

[User] Can you sort the results by booking_time in descending order and limit to the 10 most recent?

[Assistant]
SELECT b.booking_id, b.trip_id, p.first_name, p.last_name, b.booking_time, b.status
FROM transportation.bookings b
JOIN transportation.passengers p ON b.passenger_id = p.passenger_id
WHERE b.status IN ('Pending', 'Confirmed')
ORDER BY b.booking_time DESC
LIMIT 10;

[User] For each trip, can you show the trip_id, number of passengers, and the make and model of the assigned vehicle?

[Assistant]
SELECT b.trip_id, COUNT(b.passenger_id) AS passenger_count, v.make, v.model
FROM transportation.bookings b
JOIN transportation.vehicles v ON b.trip_id IN (
    SELECT DISTINCT trip_id FROM transportation.fuel_logs WHERE vehicle_id = v.vehicle_id
)
GROUP BY b.trip_id, v.make, v.model;

[User] Show me the trip_id, route_number, and scheduled_departure for all trips where the associated vehicle has a maintenance log indicating the next service is due before 2024-05-01.

[Assistant]
SELECT t.trip_id, r.route_number, t.scheduled_departure
FROM transportation.trips t
JOIN transportation.routes r ON t.route_id = r.route_id
JOIN transportation.maintenance_logs m ON t.vehicle_id = m.vehicle_id
WHERE m.next_service_due_date < '2024-05-01';

[User] For the above list, also include the mechanic_name from the maintenance log.

[Assistant]
SELECT t.trip_id, r.route_number, t.scheduled_departure, m.mechanic_name
FROM transportation.trips t
JOIN transportation.routes r ON t.route_id = r.route_id
JOIN transportation.maintenance_logs m ON t.vehicle_id = m.vehicle_id
WHERE m.next_service_due_date < '2024-05-01';


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE 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 PRIMARY KEY, patient_id text, doctor_id text, appointment_time timestamp, duration_minutes int, 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.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] Show me all male patients who have received more than one prescription, including their full name, date of birth, and the total number of prescriptions.

[Assistant]
SELECT p.patient_id, p.first_name, p.last_name, p.date_of_birth, COUNT(pr.prescription_id) AS total_prescriptions
FROM healthcare.patients p
JOIN healthcare.prescriptions pr ON p.patient_id = pr.patient_id
WHERE p.gender = 'Male'
GROUP BY p.patient_id, p.first_name, p.last_name, p.date_of_birth
HAVING COUNT(pr.prescription_id) > 1;

[User] Could you also include the names of the medications they've been prescribed?

[Assistant]
SELECT p.patient_id, p.first_name, p.last_name, p.date_of_birth, COUNT(pr.prescription_id) AS total_prescriptions, STRING_AGG(pr.medication_id, ', ') AS medication_ids
FROM healthcare.patients p
JOIN healthcare.prescriptions pr ON p.patient_id = pr.patient_id
WHERE p.gender = 'Male'
GROUP BY p.patient_id, p.first_name, p.last_name, p.date_of_birth
HAVING COUNT(pr.prescription_id) > 1;

[User] Actually, I only want to see patients who also have at least one active diagnosis.

[Assistant]
SELECT p.patient_id, p.first_name, p.last_name, p.date_of_birth, COUNT(pr.prescription_id) AS total_prescriptions, STRING_AGG(DISTINCT pr.medication_id, ', ') AS medication_ids
FROM healthcare.patients p
JOIN healthcare.prescriptions pr ON p.patient_id = pr.patient_id
JOIN healthcare.diagnoses d ON p.patient_id = d.patient_id
WHERE p.gender = 'Male' AND d.status = 'Active'
GROUP BY p.patient_id, p.first_name, p.last_name, p.date_of_birth
HAVING COUNT(pr.prescription_id) > 1;

[User] One of the medication_ids columns seems off, could you instead also show the medication_id and dosage for each prescription individually, as well as the diagnosis_code for their active diagnosis?

[Assistant]
SELECT p.patient_id, p.first_name, p.last_name, p.date_of_birth, pr.prescription_id, pr.medication_id, pr.dosage, d.diagnosis_code
FROM healthcare.patients p
JOIN healthcare.prescriptions pr ON p.patient_id = pr.patient_id
JOIN healthcare.diagnoses d ON p.patient_id = d.patient_id
WHERE p.gender = 'Male' AND d.status = 'Active';

[User] Show all prescriptions made in 2024 for medications prescribed during appointments scheduled at location 'LOC001', including prescription_id, patient_id, medication_id, and appointment_time.

[Assistant]
SELECT pr.prescription_id, pr.patient_id, pr.medication_id, ap.appointment_time
FROM healthcare.prescriptions pr
JOIN healthcare.medical_records mr ON pr.record_id = mr.record_id
JOIN healthcare.appointments ap ON mr.appointment_id = ap.appointment_id
WHERE ap.location_id = 'LOC001'
  AND EXTRACT(YEAR FROM pr.prescription_date) = 2024;

[User] List the contact phone and website for all insurance plans provided by 'Continental Health'.

[Assistant]
SELECT plan_name, contact_phone, website
FROM healthcare.insurance_plans
WHERE insurance_provider = 'Continental Health';

[User] List all medical record IDs and the record date for records created by doctors specializing in 'Gastroenterology'.

[Assistant] SELECT mr.record_id, mr.record_date FROM healthcare.medical_records mr JOIN healthcare.doctors d ON mr.doctor_id = d.doctor_id WHERE d.specialty = 'Gastroenterology';

[User] Could you also include the patient's first and last name for these records?

[Assistant] SELECT mr.record_id, mr.record_date, p.first_name, p.last_name FROM healthcare.medical_records mr JOIN healthcare.doctors d ON mr.doctor_id = d.doctor_id JOIN healthcare.patients p ON mr.patient_id = p.patient_id WHERE d.specialty = 'Gastroenterology';

[User] Now, only show records for male patients.

[Assistant] SELECT mr.record_id, mr.record_date, p.first_name, p.last_name FROM healthcare.medical_records mr JOIN healthcare.doctors d ON mr.doctor_id = d.doctor_id JOIN healthcare.patients p ON mr.patient_id = p.patient_id WHERE d.specialty = 'Gastroenterology' AND p.gender = 'Male';

[User] Additionally, restrict the results to medical records that have at least one associated diagnosis with status 'Resolved'.

[Assistant] SELECT DISTINCT mr.record_id, mr.record_date, p.first_name, p.last_name FROM healthcare.medical_records mr JOIN healthcare.doctors d ON mr.doctor_id = d.doctor_id JOIN healthcare.patients p ON mr.patient_id = p.patient_id JOIN healthcare.diagnoses diag ON mr.record_id = diag.record_id WHERE d.specialty = 'Gastroenterology' AND p.gender = 'Male' AND diag.status = 'Resolved';

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

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

[User] List each chronic active diagnosis along with the prescribed medication details, showing diagnosis_id, diagnosis_code, medication_id, dosage, and diagnosis_date.

[Assistant] SELECT d.diagnosis_id, d.diagnosis_code, p.medication_id, p.dosage, d.diagnosis_date FROM healthcare.diagnoses d JOIN healthcare.prescriptions p ON d.record_id = p.record_id AND d.patient_id = p.patient_id WHERE d.is_chronic = TRUE AND d.status = 'Active';