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.customers ( customer_id.text, first_name.text, last_name.text, date_of_birth.date, ssn_hash.text, address_line1.text, address_line2.text, city.text, state.text, zip_code.text, country.text, phone_number.text, email.text, created_at.timestamp, updated_at.timestamp, status.text )
CREATE TABLE insurance.agents ( agent_id character varying(64) NOT NULL, first_name character varying(100) NOT NULL, last_name character varying(100) NOT NULL, agency_name character varying(150), license_number character varying(100) NOT NULL UNIQUE, license_state character varying(50) NOT NULL, contact_email character varying(128) UNIQUE, contact_phone character varying(30), hire_date date, termination_date date, status character varying(20) NOT NULL DEFAULT 'Active', commission_rate numeric(5, 4) NOT NULL DEFAULT 0.05, manager_id character varying(64), PRIMARY KEY (agent_id) )
CREATE TABLE insurance.claim_documents ( document_id text PRIMARY KEY, claim_id text, document_type text, file_name text, file_path text, file_size_bytes int, mime_type text, uploaded_by text, uploaded_at timestamp, description text )
##Table Structure
CREATE TABLE hospitality_technology.staff ( staff_id character varying(64) NOT NULL, property_id character varying(64) NOT NULL, first_name character varying(100) NOT NULL, last_name character varying(100) NOT NULL, position character varying(100) NOT NULL, work_email character varying(255) UNIQUE, work_phone character varying(30), hire_date date NOT NULL, termination_date date, is_active boolean NOT NULL DEFAULT true, access_level integer NOT NULL, manager_id character varying(64), created_at timestamp with time zone NOT NULL DEFAULT current_timestamp, PRIMARY KEY (staff_id), FOREIGN KEY (property_id) REFERENCES hospitality_technology.properties(property_id), FOREIGN KEY (manager_id) REFERENCES hospitality_technology.staff(staff_id) )
##Table Structure
CREATE TABLE gaming_technology.developers ( developer_id uuid, name text, country text, founded_year integer, website text, created_at timestamp with time zone )
##Table Structure
CREATE TABLE legal_services.documents ( document_id.text, case_id.text, document_name.text, document_type.text, storage_path.text, uploaded_by_lawyer_id.text, upload_timestamp.timestamp, version.integer, description.text )
##Table Structure
CREATE TABLE transportation.locations ( location_id.text, name.text, type.text, address_line1.text, city.text, state_province.text, postal_code.text, country.text, latitude.numeric, longitude.numeric, timezone.text )
##Table Structure
CREATE TABLE trading_platform.wallets ( wallet_id.text, user_id.text, address.text, private_key.text, created_at.timestamp )
CREATE TABLE trading_platform.orders ( order_id.text, user_id.text, wallet_id.text, asset_id.text, order_type.text, quantity.numeric, price.numeric, status.text, created_at.timestamp )
CREATE TABLE trading_platform.trades ( trade_id.text, order_id.text, buyer_id.text, seller_id.text, asset_id.text, quantity.numeric, price.numeric, traded_at.timestamp )
CREATE TABLE trading_platform.utxos ( utxo_id.text, transaction_id.text, output_index.integer, address.text, amount.numeric, spent.boolean )

[User] Which claims have at least one document uploaded by an agent located in 'NY'? Show the claim_id, document_type, file_name, uploaded_by, and the agent's first and last name.

[Assistant]
SELECT cd.claim_id, cd.document_type, cd.file_name, cd.uploaded_by, a.first_name, a.last_name
FROM insurance.claim_documents cd
JOIN insurance.agents a ON cd.uploaded_by = a.agent_id
WHERE a.license_state = 'NY';

[User] Show me all active staff including their staff_id, first_name, last_name, position, and work_email.

[Assistant]
SELECT staff_id,
       first_name,
       last_name,
       position,
       work_email
FROM hospitality_technology.staff
WHERE is_active = true;

[User] Actually, I need the results sorted by hire_date descending.

[Assistant]
SELECT staff_id,
       first_name,
       last_name,
       position,
       work_email
FROM hospitality_technology.staff
WHERE is_active = true
ORDER BY hire_date DESC;

[User] List all developer names and their countries.

[Assistant] SELECT name, country FROM gaming_technology.developers;

[User] Filter the list to only include developers from countries that start with 'U'.

[Assistant] SELECT name, country FROM gaming_technology.developers WHERE country LIKE 'U%';

[User] For these developers from countries starting with 'U', what are the minimum and maximum founded years?

[Assistant] SELECT MIN(founded_year), MAX(founded_year) FROM gaming_technology.developers WHERE country LIKE 'U%';

[User] Also, include the average founded year and the total count of developers in this filtered group.

[Assistant] SELECT COUNT(*), AVG(founded_year), MIN(founded_year), MAX(founded_year) FROM gaming_technology.developers WHERE country LIKE 'U%';

[User] For each document (identified by case_id and document_name), find the latest version number and the ID of the lawyer who uploaded that version.

[Assistant] WITH RankedDocuments AS ( SELECT document_id, case_id, document_name, uploaded_by_lawyer_id, version, ROW_NUMBER() OVER(PARTITION BY case_id, document_name ORDER BY version DESC) as rn FROM legal_services.documents ) SELECT case_id, document_name, version AS latest_version, uploaded_by_lawyer_id AS latest_version_lawyer_id FROM RankedDocuments WHERE rn = 1;

[User] Now, filter these results to only show documents where the very first version (version 1) was uploaded by a different lawyer than the latest version you just listed.

[Assistant] SELECT vi_first.case_id, vi_first.document_name, vi_first.uploaded_by_lawyer_id AS first_version_lawyer_id, vi_latest.uploaded_by_lawyer_id AS latest_version_lawyer_id FROM legal_services.documents vi_first JOIN legal_services.documents vi_latest ON vi_first.case_id = vi_latest.case_id AND vi_first.document_name = vi_latest.document_name JOIN ( SELECT case_id, document_name, MIN(version) AS min_v, MAX(version) AS max_v FROM legal_services.documents GROUP BY case_id, document_name ) AS versions ON vi_first.case_id = versions.case_id AND vi_first.document_name = versions.document_name AND vi_first.version = versions.min_v AND vi_latest.version = versions.max_v WHERE vi_first.uploaded_by_lawyer_id <> vi_latest.uploaded_by_lawyer_id;

[User] Could you also include the upload timestamps for both the first version and the latest version for these documents?

[Assistant] SELECT vi_first.case_id, vi_first.document_name, vi_first.uploaded_by_lawyer_id AS first_version_lawyer_id, vi_first.upload_timestamp AS first_version_timestamp, vi_latest.uploaded_by_lawyer_id AS latest_version_lawyer_id, vi_latest.upload_timestamp AS latest_version_timestamp FROM legal_services.documents vi_first JOIN legal_services.documents vi_latest ON vi_first.case_id = vi_latest.case_id AND vi_first.document_name = vi_latest.document_name JOIN ( SELECT case_id, document_name, MIN(version) AS min_v, MAX(version) AS max_v FROM legal_services.documents GROUP BY case_id, document_name ) AS versions ON vi_first.case_id = versions.case_id AND vi_first.document_name = versions.document_name AND vi_first.version = versions.min_v AND vi_latest.version = versions.max_v WHERE vi_first.uploaded_by_lawyer_id <> vi_latest.uploaded_by_lawyer_id;

[User] List all locations located in the state of 'Florida'.

[Assistant] SELECT * FROM transportation.locations WHERE state_province = 'Florida';

[User] Can you only show locations of type 'Airport' or 'Hangar'?

[Assistant] SELECT * FROM transportation.locations WHERE state_province = 'Florida' AND type IN ('Airport', 'Hangar');

[User] Also, include their latitude and longitude and sort the results by city.

[Assistant] SELECT location_id, name, type, city, latitude, longitude FROM transportation.locations WHERE state_province = 'Florida' AND type IN ('Airport', 'Hangar') ORDER BY city;

[User] Actually, I only want locations in the city of 'Orlando'. Can you filter by city instead of state?

[Assistant] SELECT location_id, name, type, city, latitude, longitude FROM transportation.locations WHERE city = 'Orlando' AND type IN ('Airport', 'Hangar') ORDER BY city;

[User] List all UTXOs with amount greater than 100 and also include the address and transaction_id.

[Assistant]
SELECT utxo_id, address, transaction_id, amount
FROM trading_platform.utxos
WHERE amount > 100;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement. ##Table Structure
CREATE TABLE 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)
)
##Table Structure
CREATE TABLE social_media.comments ( comment_id text PRIMARY KEY, post_id text, user_id text, parent_comment_id text, content text, created_at timestamp, updated_at timestamp )
CREATE TABLE social_media.likes ( like_id text PRIMARY KEY, user_id text, post_id text, comment_id text, created_at timestamp )
CREATE TABLE social_media.follows ( follow_id text PRIMARY KEY, follower_user_id text, following_user_id text, created_at timestamp )
CREATE TABLE social_media.hashtags ( hashtag_id text PRIMARY KEY, tag_name text, created_at timestamp )
CREATE TABLE social_media.post_hashtags ( post_hashtag_id text PRIMARY KEY, post_id text, hashtag_id text )
CREATE TABLE social_media.messages ( message_id text PRIMARY KEY, conversation_id text, sender_user_id text, content text, media_url text, media_type text, sent_at timestamp, read_at timestamp )
CREATE TABLE social_media.conversation_participants ( participant_id text PRIMARY KEY, conversation_id text, user_id text, joined_at timestamp, last_read_at timestamp )
CREATE TABLE social_media.notifications ( notification_id text PRIMARY KEY, recipient_user_id text, sender_user_id text, notification_type text, target_entity_id text, target_entity_type text, created_at timestamp, read_at timestamp )
CREATE TABLE social_media.user_settings ( setting_id text PRIMARY KEY, user_id text, theme text, email_notifications_enabled bool, push_notifications_enabled bool, private_profile bool, updated_at timestamp )
##Table Structure
CREATE TABLE insurance.insurance_products ( product_id.text, product_name.text, product_type.text, description.text, base_premium.numeric, coverage_details.text, underwriting_rules.text, is_active.boolean, created_at.timestamp, updated_at.timestamp )
CREATE TABLE insurance.claim_documents ( document_id text PRIMARY KEY, claim_id text, document_type text, file_name text, file_path text, file_size_bytes int, mime_type text, uploaded_by text, uploaded_at timestamp, description text )
CREATE TABLE insurance.policy_beneficiaries ( beneficiary_id character varying(64) NOT NULL, policy_id character varying(64) NOT NULL, customer_id character varying(64) NOT NULL, first_name character varying(100) NOT NULL, last_name character varying(100) NOT NULL, relationship character varying(50) NOT NULL, percentage_share numeric(5, 2) NOT NULL CHECK (percentage_share > 0 AND percentage_share <= 100), contact_info text, added_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, PRIMARY KEY (beneficiary_id), UNIQUE (policy_id, customer_id) )

[User] Count the total number of likes on posts versus likes on comments across the entire platform.

[Assistant] SELECT CASE WHEN post_id IS NOT NULL THEN 'post' ELSE 'comment' END AS like_target, COUNT(*) AS total_likes FROM social_media.likes GROUP BY like_target;

[User] Show all users who follow both user 'U100' and user 'U101'.

[Assistant]
SELECT f1.follower_user_id
FROM social_media.follows f1
JOIN social_media.follows f2 ON f1.follower_user_id = f2.follower_user_id
WHERE f1.following_user_id = 'U100' AND f2.following_user_id = 'U101';

[User] List the product_id, product_name, and description of any insurance products created before 2024 whose description contains the word 'theft'.

[Assistant]
SELECT product_id, product_name, description
FROM insurance.insurance_products
WHERE created_at < '2024-01-01'
  AND description ILIKE '%theft%';


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement. ##Table Structure
CREATE TABLE gaming_technology.servers ( server_id uuid 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 )
##Table Structure
CREATE TABLE financial_services.customers ( customer_id.text, first_name.text, last_name.text, date_of_birth.date, ssn_hash.text, address.text, city.text, state.text, zip_code.text, country.text, email.text, phone_number.text, created_at.timestamp, status.text, risk_profile.text )
##Table Structure
CREATE TABLE trading_platform.users ( user_id.text, username.text, email.text, password_hash.text, created_at.timestamp )
CREATE TABLE trading_platform.assets ( asset_id text, name text, symbol text, type text )
CREATE TABLE trading_platform.utxos ( utxo_id text PRIMARY KEY, transaction_id text, output_index int, address text, amount numeric, spent boolean )
CREATE TABLE trading_platform.dapps ( dapp_id text, name text, description text, url text )
CREATE TABLE trading_platform.peers ( peer_id.text, ip_address.text, port.integer, last_seen.timestamp )
CREATE TABLE trading_platform.metadata ( metadata_id character varying(64) NOT NULL, asset_id character varying(64) NOT NULL, key character varying(128) NOT NULL, value text NOT NULL, PRIMARY KEY (metadata_id) )
CREATE TABLE trading_platform.kyc_audit ( kyc_audit_id.text, user_id.text, status.text, reviewed_at.timestamp )
CREATE TABLE trading_platform.logs ( log_id text PRIMARY KEY, user_id text, action text, details text, logged_at timestamp )
CREATE TABLE trading_platform.notifications ( notification_id text, user_id text, message text, sent_at timestamp, read_at timestamp )
##Table Structure
CREATE TABLE hospitality_technology.properties ( property_id text PRIMARY KEY, property_name text, address_line1 text, address_line2 text, city text, state_province text, postal_code text, country_code text, phone_number text, email_address text, property_type text, star_rating numeric, timezone text, manager_staff_id text, created_at timestamp, updated_at timestamp )
CREATE TABLE hospitality_technology.rooms ( room_id text PRIMARY KEY, property_id text, room_number text, room_type_id text, floor int, status text, is_smoking boolean, features text, current_condition text, last_cleaned_at timestamp )
##Table Structure
CREATE TABLE hospitality_technology.staff (
    staff_id character varying(64) NOT NULL,  -- unique identifier for the staff member
    property_id character varying(64) NOT NULL, -- FK to properties table (primary property)
    first_name character varying(100) NOT NULL,
    last_name character varying(100) NOT NULL,
    position character varying(100) NOT NULL, -- e.g., Front Desk Agent, Housekeeper, Manager, Concierge
    work_email character varying(255) UNIQUE, -- staff member's work email
    work_phone character varying(30),
    hire_date date NOT NULL,
    termination_date date, -- date employment ended (if applicable)
    is_active boolean NOT NULL DEFAULT true, -- currently employed flag
    access_level integer NOT NULL, -- permission level within systems (e.g., 1=basic, 5=admin)
    manager_id character varying(64), -- FK to staff table (self-referencing for supervisor)
    created_at timestamp with time zone NOT NULL DEFAULT current_timestamp,
    PRIMARY KEY (staff_id),
    FOREIGN KEY (property_id) REFERENCES hospitality_technology.properties(property_id),
    FOREIGN KEY (manager_id) REFERENCES hospitality_technology.staff(staff_id)
)

[User] I need to find every offline server alongside an online server in the same region.

[Assistant]
SELECT s_off.server_id AS offline_id,
       s_on.server_id AS online_id
FROM gaming_technology.servers s_off
JOIN gaming_technology.servers s_on
  ON s_off.region = s_on.region
WHERE s_off.status = 'offline'
  AND s_on.status = 'online';

[User] Include the names of both servers, labeling them offline_server and online_server.

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

[User] Also add the online server's current_players and status.

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

[User] Order the results by offline_server ascending.

[Assistant]
SELECT s_off.server_name AS offline_server,
       s_on.server_name AS online_server,
       s_on.current_players,
       s_on.status AS online_status
FROM gaming_technology.servers s_off
JOIN gaming_technology.servers s_on
  ON s_off.region = s_on.region
WHERE s_off.status = 'offline'
  AND s_on.status = 'online'
ORDER BY offline_server ASC;

[User] List all pairs of customers who have the same last name but live in different states. Show both customer ids, their full names, and their states.

[Assistant]
SELECT a.customer_id AS customer_id_a, a.first_name AS first_name_a, a.last_name AS last_name, a.state AS state_a, b.customer_id AS customer_id_b, b.first_name AS first_name_b, b.state AS state_b
FROM financial_services.customers a
JOIN financial_services.customers b
  ON a.last_name = b.last_name
  AND a.customer_id < b.customer_id
  AND a.state <> b.state;

[User] Also, show the city for each customer in the result.

[Assistant]
SELECT a.customer_id AS customer_id_a, a.first_name AS first_name_a, a.last_name AS last_name, a.state AS state_a, a.city AS city_a, b.customer_id AS customer_id_b, b.first_name AS first_name_b, b.state AS state_b, b.city AS city_b
FROM financial_services.customers a
JOIN financial_services.customers b
  ON a.last_name = b.last_name
  AND a.customer_id < b.customer_id
  AND a.state <> b.state;

[User] Show each user's username along with their KYC status and the date of their latest KYC review.

[Assistant]
SELECT u.username, ka.status, ka.reviewed_at AS latest_review
FROM trading_platform.users u
JOIN trading_platform.kyc_audit ka ON u.user_id = ka.user_id
WHERE ka.reviewed_at = (
  SELECT MAX(reviewed_at)
  FROM trading_platform.kyc_audit
  WHERE user_id = u.user_id
);

[User] Also filter to only include those whose latest status is 'approved'.

[Assistant]
SELECT u.username, ka.status, ka.reviewed_at AS latest_review
FROM trading_platform.users u
JOIN trading_platform.kyc_audit ka ON u.user_id = ka.user_id
WHERE ka.reviewed_at = (
  SELECT MAX(reviewed_at)
  FROM trading_platform.kyc_audit
  WHERE user_id = u.user_id
)
  AND ka.status = 'approved';

[User] List each property_name along with the count of rooms that are currently marked as 'Available'.

[Assistant]
SELECT p.property_name, COUNT(r.room_id) AS available_room_count
FROM hospitality_technology.properties p
LEFT JOIN hospitality_technology.rooms r
  ON p.property_id = r.property_id AND r.status = 'Available'
GROUP BY p.property_name;

[User] Only include properties with more than 10 available rooms and order by available_room_count descending.

[Assistant]
SELECT p.property_name, COUNT(r.room_id) AS available_room_count
FROM hospitality_technology.properties p
LEFT JOIN hospitality_technology.rooms r
  ON p.property_id = r.property_id AND r.status = 'Available'
GROUP BY p.property_name
HAVING COUNT(r.room_id) > 10
ORDER BY available_room_count DESC;

[User] Which staff members have never been assigned a manager? List their full names and property IDs.

[Assistant]
SELECT staff_id, first_name, last_name, property_id
FROM hospitality_technology.staff
WHERE manager_id IS NULL;

[User] Also include their work email and only show currently active staff.

[Assistant]
SELECT staff_id, first_name, last_name, property_id, work_email
FROM hospitality_technology.staff
WHERE manager_id IS NULL AND is_active = true;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement. ##Table Structure
CREATE TABLE government_services.citizens ( citizen_id character varying(64) NOT NULL, national_id_number character varying(128) NOT NULL UNIQUE, first_name character varying(100) NOT NULL, last_name character varying(100) NOT NULL, date_of_birth date NOT NULL, gender character varying(20), primary_address text NOT NULL, contact_email character varying(128) UNIQUE, contact_phone character varying(32), registration_date timestamp NOT NULL, is_verified boolean DEFAULT false, PRIMARY KEY (citizen_id) )
CREATE TABLE government_services.agencies ( agency_id text PRIMARY KEY, agency_name text, jurisdiction_level text, primary_contact_email text, main_phone_number text, website_url text, established_date date, parent_agency_id text )
CREATE TABLE government_services.applications ( application_id text, 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.documents ( document_id character varying(64) NOT NULL, application_id character varying(64), citizen_id character varying(64) NOT NULL, document_type character varying(100) NOT NULL, file_reference text NOT NULL, upload_timestamp timestamp NOT NULL, expiry_date date, verification_status character varying(30) DEFAULT 'Pending', verified_by_employee_id character varying(64), verification_timestamp timestamp, PRIMARY KEY (document_id) )
CREATE TABLE government_services.employees ( employee_id.text, agency_id.text, first_name.text, last_name.text, job_title.text, department.text, work_email.text, work_phone.text, hire_date.date, termination_date.date, access_level.text, manager_employee_id.text )
CREATE TABLE government_services.service_locations ( location_id.text, agency_id.text, location_name.text, address.text, city.text, state.text, postal_code.text, latitude.numeric, longitude.numeric, operating_hours.text, contact_phone.text, is_accessible.boolean )
CREATE TABLE government_services.appointments ( appointment_id text, 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, 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 )
##Table Structure
CREATE TABLE legal_services.clients ( client_id character varying(64) NOT NULL, first_name character varying(100) NOT NULL, last_name character varying(100) NOT NULL, company_name character varying(200), email character varying(128) UNIQUE NOT NULL, phone character varying(32), address text, date_registered timestamp NOT NULL, status character varying(32) NOT NULL, PRIMARY KEY (client_id) )
CREATE TABLE legal_services.lawyers ( lawyer_id text PRIMARY KEY, first_name text, last_name text, bar_number text UNIQUE, firm_id text, email text UNIQUE, phone text, specialization text, hire_date timestamp, is_partner bool )
CREATE TABLE legal_services.law_firms ( firm_id text, firm_name text, address text, phone text, website text, founded_date date, managing_partner_id text )
CREATE TABLE legal_services.cases ( case_id character varying(64) NOT NULL, case_number character varying(100) UNIQUE, case_name text NOT NULL, client_id character varying(64) NOT NULL, lead_lawyer_id character varying(64) NOT NULL, case_type character varying(100) NOT NULL, status character varying(50) NOT NULL, date_opened timestamp NOT NULL, date_closed timestamp, description text, court_jurisdiction character varying(128), PRIMARY KEY (case_id) )
CREATE TABLE legal_services.time_entries (
    entry_id character varying(64) NOT NULL,  -- unique identifier for the time entry
    case_id character varying(64) NOT NULL, -- FK to cases table
    lawyer_id character varying(64) NOT NULL, -- FK to lawyers table (who performed the work)
    date_worked date NOT NULL, -- date the work was performed
    hours_spent numeric(5, 2) NOT NULL CHECK (hours_spent > 0), -- duration of work in hours (e.g., 1.5 for 1h 30m)
    billing_rate numeric(10, 2) NOT NULL, -- hourly rate applied for this entry
    description text NOT NULL, -- detailed description of the work performed
    is_billable boolean DEFAULT true, -- whether this time entry is billable to the client
    is_billed boolean DEFAULT false, -- whether this entry has been included in an invoice
    invoice_id character varying(64), -- FK to invoices table (once billed)
    created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, -- when the entry was recorded
    PRIMARY KEY (entry_id)
)
CREATE TABLE legal_services.invoices ( invoice_id text PRIMARY KEY, invoice_number text UNIQUE, client_id text, case_id text, issue_date date, due_date date, total_amount numeric, amount_paid numeric, status text, payment_date timestamp, notes text, created_at timestamp )
CREATE TABLE legal_services.appointments ( appointment_id text PRIMARY KEY, client_id text, lawyer_id text, case_id text, start_time timestamp, end_time timestamp, location text, subject text, notes text, status text, created_at timestamp )
##Table Structure
CREATE TABLE trading_platform.users ( user_id text PRIMARY KEY, username text, email text, password_hash text, created_at timestamp )
CREATE TABLE trading_platform.wallets ( wallet_id text PRIMARY KEY, user_id text, address text, private_key text, created_at timestamp )
CREATE TABLE trading_platform.trades ( trade_id text PRIMARY KEY, order_id text, buyer_id text, seller_id text, asset_id text, quantity numeric, price numeric, traded_at timestamp )
CREATE TABLE trading_platform.assets ( asset_id text PRIMARY KEY, name text, symbol text, type text )
CREATE TABLE trading_platform.utxos ( utxo_id text PRIMARY KEY, transaction_id text, output_index int, address text, amount numeric, spent boolean )
CREATE TABLE trading_platform.dapps ( dapp_id text PRIMARY KEY, name text, description text, url text )
CREATE TABLE trading_platform.peers ( peer_id text PRIMARY KEY, ip_address text, port int, last_seen timestamp )
CREATE TABLE trading_platform.metadata ( metadata_id text PRIMARY KEY, asset_id text, key text, value text )
CREATE TABLE trading_platform.kyc_audit ( kyc_audit_id text PRIMARY KEY, user_id text, status text, reviewed_at timestamp )
CREATE TABLE trading_platform.logs ( log_id text PRIMARY KEY, user_id text, action text, details text, logged_at timestamp )
CREATE TABLE trading_platform.notifications ( notification_id text PRIMARY KEY, user_id text, message text, sent_at timestamp, read_at timestamp )
##Table Structure
CREATE TABLE web3.wallets ( wallet_id.text, user_id.text, address.text, private_key.text, created_at.timestamp )

[User] How many applications are currently in 'Processing' status? Return the total count.

[Assistant]
SELECT COUNT(*) AS processing_applications_count
FROM government_services.applications
WHERE status = 'Processing';

[User] Display all invoices along with the associated case name and the full name of the client.

[Assistant]
SELECT i.invoice_number, cs.case_name, c.first_name || ' ' || c.last_name AS client_full_name
FROM legal_services.invoices i
LEFT JOIN legal_services.cases cs ON i.case_id = cs.case_id
LEFT JOIN legal_services.clients c ON i.client_id = c.client_id;

[User] List users and their latest wallet address if they have one, ordered by username.

[Assistant] SELECT u.username, w.address FROM users u JOIN wallets w ON u.user_id = w.user_id WHERE w.created_at = (SELECT MAX(w2.created_at) FROM wallets w2 WHERE w2.user_id = u.user_id) ORDER BY u.username;

[User] Filter that list to only include users created after '2023-01-01'.

[Assistant] SELECT u.username, w.address FROM users u JOIN wallets w ON u.user_id = w.user_id WHERE w.created_at = (SELECT MAX(w2.created_at) FROM wallets w2 WHERE w2.user_id = u.user_id) AND u.created_at > '2023-01-01' ORDER BY u.username;

[User] List the wallet IDs and creation timestamps for all wallets created after '2023-01-01'.

[Assistant] SELECT wallet_id, created_at FROM web3.wallets WHERE created_at > '2023-01-01';

[User] Can you modify that to only show wallets for user ID 'user_123' and include the wallet address?

[Assistant] SELECT wallet_id, address, created_at FROM web3.wallets WHERE created_at > '2023-01-01' AND user_id = 'user_123';


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement. ##Table Structure
CREATE TABLE hospitality_technology.properties ( property_id text PRIMARY KEY, property_name text, address_line1 text, address_line2 text, city text, state_province text, postal_code text, country_code text, phone_number text, email_address text, property_type text, star_rating numeric, timezone text, manager_staff_id text, created_at timestamp, updated_at timestamp )
CREATE TABLE hospitality_technology.guests ( guest_id.text, first_name.text, last_name.text, email.text, phone_number.text, date_of_birth.date, address_line1.text, city.text, state_province.text, postal_code.text, country_code.text, preferences.text, loyalty_member_id.text, communication_consent.boolean, created_at.timestamp, updated_at.timestamp )
CREATE TABLE hospitality_technology.payments ( payment_id text, reservation_id text, guest_id text, bill_id text, amount numeric, currency_code text, payment_method text, card_type text, card_last_four text, transaction_ref text, payment_timestamp timestamp, status text, staff_id_processed text, notes text )
##Table Structure
CREATE TABLE transportation.drivers ( driver_id text, employee_id text, first_name text, last_name text, license_number text, license_expiry_date date, contact_number text, email text, hire_date date, status text )
CREATE TABLE transportation.trips (
    trip_id character varying(64) NOT NULL,  -- unique identifier for a specific trip instance
    route_id character varying(64), -- identifier of the route being followed (can be null for ad-hoc trips)
    vehicle_id character varying(64) NOT NULL, -- identifier of the vehicle used
    driver_id character varying(64) NOT NULL, -- identifier of the driver operating
    scheduled_departure timestamp with time zone NOT NULL, -- planned departure time
    actual_departure timestamp with time zone, -- actual departure time
    scheduled_arrival timestamp with time zone NOT NULL, -- planned arrival time
    actual_arrival timestamp with time zone, -- actual arrival time
    origin_location_id character varying(64) NOT NULL, -- actual starting location (could differ from route origin)
    destination_location_id character varying(64) NOT NULL, -- actual ending location (could differ from route destination)
    status character varying(32) NOT NULL, -- e.g., Scheduled, In Progress, Completed, Delayed, Cancelled
    passenger_count integer, -- number of passengers (if applicable)
    cargo_manifest_id character varying(64), -- link to cargo details (if applicable)
    PRIMARY KEY (trip_id)
)
CREATE TABLE transportation.locations ( location_id text, name text, type text, address_line1 text, city text, state_province text, postal_code text, country text, latitude numeric, longitude numeric, timezone text )
CREATE TABLE transportation.maintenance_logs ( log_id text PRIMARY KEY, vehicle_id text, service_date date, odometer_reading int, service_type text, description text, cost numeric, mechanic_name text, next_service_due_date date )
##Table Structure
CREATE TABLE trading_platform.users ( user_id character varying(64) NOT NULL, username character varying(128) NOT NULL, email character varying(128) NOT NULL, password_hash text NOT NULL, created_at timestamp NOT NULL, PRIMARY KEY (user_id) )
CREATE TABLE trading_platform.wallets ( wallet_id character varying(64) NOT NULL, user_id character varying(64) NOT NULL, address character varying(128) NOT NULL, private_key text NOT NULL, created_at timestamp NOT NULL, PRIMARY KEY (wallet_id) )
CREATE TABLE trading_platform.assets ( asset_id text PRIMARY KEY, name text, symbol text, type text )
CREATE TABLE trading_platform.metadata (
    metadata_id character varying(64) NOT NULL,  -- unique identifier for the metadata
    asset_id character varying(64) NOT NULL, -- identifier of the asset the metadata is associated with
    key character varying(128) NOT NULL, -- key of the metadata
    value text NOT NULL, -- value of the metadata
    PRIMARY KEY (metadata_id)
)
CREATE TABLE trading_platform.logs (
    log_id character varying(64) NOT NULL,  -- unique identifier for the log entry
    user_id character varying(64), -- identifier of the user associated with the log entry
    action character varying(128) NOT NULL, -- action performed
    details text NOT NULL, -- details of the action
    logged_at timestamp NOT NULL, -- time when the log entry was created
    PRIMARY KEY (log_id)
)
CREATE TABLE trading_platform.notifications ( notification_id text PRIMARY KEY, user_id text, message text, sent_at timestamp, read_at timestamp )
##Table Structure
CREATE TABLE gaming_technology.players ( player_id uuid PRIMARY KEY, username text, email text, password_hash text, registration_date timestamptz, last_login timestamptz, country_code text, status text, profile_data jsonb )

[User] List all guests who have a loyalty_member_id, showing their guest_id, first_name, last_name, and loyalty_member_id.

[Assistant]
SELECT guest_id,
       first_name,
       last_name,
       loyalty_member_id
FROM hospitality_technology.guests
WHERE loyalty_member_id IS NOT NULL;

[User] Now filter to only include those guests who are from Canada and order by last_name.

[Assistant]
SELECT guest_id,
       first_name,
       last_name,
       loyalty_member_id
FROM hospitality_technology.guests
WHERE loyalty_member_id IS NOT NULL
  AND country_code = 'CA'
ORDER BY last_name ASC;

[User] List all maintenance logs for vehicles that had 'Oil Change' service in the last 3 months, showing vehicle ID, service date, and cost.

[Assistant] SELECT vehicle_id, service_date, cost FROM transportation.maintenance_logs WHERE service_type = 'Oil Change' AND service_date >= CURRENT_DATE - INTERVAL '3 months';

[User] Can you include the mechanic name and show only services that cost more than $100?

[Assistant] SELECT vehicle_id, service_date, cost, mechanic_name FROM transportation.maintenance_logs WHERE service_type = 'Oil Change' AND service_date >= CURRENT_DATE - INTERVAL '3 months' AND cost > 100;

[User] Actually, I need to see the vehicle make and model as well. Can you include that information?

[Assistant] Sorry, I can't include vehicle make and model as those fields aren't present in the provided table schemas. The maintenance_logs table only contains vehicle_id but not make/model information.

[User] Then just add the odometer reading to the previous query and order by the most recent services first.

[Assistant] SELECT vehicle_id, service_date, cost, mechanic_name, odometer_reading FROM transportation.maintenance_logs WHERE service_type = 'Oil Change' AND service_date >= CURRENT_DATE - INTERVAL '3 months' AND cost > 100 ORDER BY service_date DESC;

[User] List the total number of notifications each user has received along with their user_id, username, and email.

[Assistant]
SELECT u.user_id, u.username, u.email, COUNT(n.notification_id) AS total_notifications
FROM trading_platform.users u
LEFT JOIN trading_platform.notifications n
  ON u.user_id = n.user_id
GROUP BY u.user_id, u.username, u.email;

[User] For each player, can you find the username and registration_date of the player who registered immediately before them in the same country?

[Assistant]
SELECT p.player_id,
       p.username AS current_username,
       p.registration_date,
       prev.username AS prev_username,
       prev.registration_date AS prev_registration_date
FROM gaming_technology.players p
LEFT JOIN gaming_technology.players prev
  ON p.country_code = prev.country_code
 AND prev.registration_date = (
      SELECT MAX(registration_date)
      FROM gaming_technology.players
      WHERE country_code = p.country_code
        AND registration_date < p.registration_date
    );

[User] Actually, I'd like to exclude players who don't have a previous registrant, so only show rows where prev_username is not null.

[Assistant]
SELECT p.player_id,
       p.username AS current_username,
       p.registration_date,
       prev.username AS prev_username,
       prev.registration_date AS prev_registration_date
FROM gaming_technology.players p
JOIN gaming_technology.players prev
  ON p.country_code = prev.country_code
 AND prev.registration_date = (
      SELECT MAX(registration_date)
      FROM gaming_technology.players
      WHERE country_code = p.country_code
        AND registration_date < p.registration_date
    );

[User] I'd like the final result ordered by country_code and then by the player's registration_date.

[Assistant]
SELECT p.player_id,
       p.username AS current_username,
       p.registration_date,
       prev.username AS prev_username,
       prev.registration_date AS prev_registration_date
FROM gaming_technology.players p
JOIN gaming_technology.players prev
  ON p.country_code = prev.country_code
 AND prev.registration_date = (
      SELECT MAX(registration_date)
      FROM gaming_technology.players
      WHERE country_code = p.country_code
        AND registration_date < p.registration_date
    )
ORDER BY p.country_code, p.registration_date;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement. ##Table Structure
CREATE TABLE legal_services.documents (
    document_id character varying(64) NOT NULL,  -- unique identifier for the document
    case_id character varying(64) NOT NULL, -- FK to cases table
    document_name character varying(255) NOT NULL, -- name of the document file
    document_type character varying(100), -- e.g., Pleading, Contract, Evidence, Correspondence
    storage_path text NOT NULL, -- path or reference to the document storage location
    uploaded_by_lawyer_id character varying(64), -- FK to lawyers table (who uploaded it)
    upload_timestamp timestamp NOT NULL, -- time the document was uploaded
    version integer DEFAULT 1, -- document version number
    description text, -- brief description or notes about the document
    PRIMARY KEY (document_id)
)
##Table Structure
CREATE TABLE transportation.drivers ( driver_id.text, employee_id.text, first_name.text, last_name.text, license_number.text, license_expiry_date.date, contact_number.text, email.text, hire_date.date, status.text )
##Table Structure
CREATE TABLE financial_services.accounts (
    account_id character varying(64) NOT NULL, -- unique identifier for the account
    customer_id character varying(64) NOT NULL, -- foreign key linking to the customer
    account_number character varying(128) NOT NULL UNIQUE, -- unique account number visible to customer
    account_type character varying(50) NOT NULL, -- e.g., Checking, Savings, Investment, Loan, Credit Card
    balance numeric(19, 4) NOT NULL DEFAULT 0.00, -- current account balance
    currency character varying(3) NOT NULL, -- currency code (e.g., USD, EUR)
    opened_date date NOT NULL, -- date the account was opened
    status character varying(32) NOT NULL, -- e.g., Open, Closed, Frozen
    interest_rate numeric(5, 4), -- annual interest rate, if applicable
    last_updated_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, -- timestamp of last account update
    PRIMARY KEY (account_id),
    FOREIGN KEY (customer_id) REFERENCES financial_services.customers(customer_id)
)
##Table Structure
CREATE TABLE trading_platform.dapps (
    dapp_id character varying(64) NOT NULL,  -- unique identifier for the DApp
    name character varying(128) NOT NULL, -- name of the DApp
    description text NOT NULL, -- description of the DApp
    url character varying(256) NOT NULL, -- URL of the DApp
    PRIMARY KEY (dapp_id)
)
CREATE TABLE trading_platform.kyc_audit (
    kyc_audit_id character varying(64) NOT NULL,  -- unique identifier for the KYC audit
    user_id character varying(64) NOT NULL, -- identifier of the user being audited
    status character varying(32) NOT NULL, -- status of the KYC audit (e.g., pending, approved, rejected)
    reviewed_at timestamp NOT NULL, -- time when the KYC audit was reviewed
    PRIMARY KEY (kyc_audit_id)
)
##Table Structure
CREATE TABLE healthcare.patients ( patient_id text, first_name text, last_name text, date_of_birth date, gender text, address text, phone_number text, email text, emergency_contact_name text, emergency_contact_phone text, created_at timestamp, updated_at timestamp )
CREATE TABLE healthcare.doctors ( doctor_id text, first_name text, last_name text, specialty text, license_number text, phone_number text, email text, hospital_affiliation_id text, created_at timestamp, updated_at timestamp )
CREATE TABLE healthcare.medical_records ( record_id.text, patient_id.text, appointment_id.text, doctor_id.text, record_date.timestamp, chief_complaint.text, present_illness_history.text, past_medical_history.text, physical_examination_notes.text, assessment.text, treatment_plan.text, vitals.json, created_at.timestamp )
CREATE TABLE healthcare.diagnoses ( diagnosis_id text, record_id text, patient_id text, doctor_id text, diagnosis_code text, code_type text, description text, diagnosis_date date, status text, is_chronic boolean )
CREATE TABLE healthcare.prescriptions ( prescription_id text, record_id text, patient_id text, doctor_id text, medication_id text, dosage text, frequency text, route text, start_date date, end_date date, quantity_dispensed numeric, refills_allowed integer, prescription_date timestamp )
CREATE TABLE healthcare.patient_insurance ( patient_insurance_id text, patient_id text, plan_id text, policy_number text, group_number text, subscriber_name text, effective_date date, expiration_date date, is_primary boolean )

[User] Show me document names and upload timestamps for documents linked to cases that were opened after January 1, 2023.

[Assistant] SELECT T1.document_name, T1.upload_timestamp FROM documents AS T1 JOIN cases AS T2 ON T1.case_id = T2.case_id WHERE T2.date_opened > '2023-01-01';

[User] Additionally, only include documents that have a version number greater than 1.

[Assistant] SELECT T1.document_name, T1.upload_timestamp FROM documents AS T1 JOIN cases AS T2 ON T1.case_id = T2.case_id WHERE T2.date_opened > '2023-01-01' AND T1.version > 1;

[User] For each driver, show their driver_id, first_name, last_name, along with any other driver whose license_expiry_date is earlier than theirs.

[Assistant]
SELECT d1.driver_id       AS driver_id,
       d1.first_name,
       d1.last_name,
       d2.driver_id       AS earlier_driver_id,
       d2.license_expiry_date AS earlier_expiry_date
FROM transportation.drivers d1
JOIN transportation.drivers d2
  ON d2.license_expiry_date < d1.license_expiry_date;

[User] Exclude pairs where the two expiry dates are not in the same calendar year.

[Assistant]
SELECT d1.driver_id       AS driver_id,
       d1.first_name,
       d1.last_name,
       d2.driver_id       AS earlier_driver_id,
       d2.license_expiry_date AS earlier_expiry_date
FROM transportation.drivers d1
JOIN transportation.drivers d2
  ON d2.license_expiry_date < d1.license_expiry_date
     AND EXTRACT(YEAR FROM d1.license_expiry_date) = EXTRACT(YEAR FROM d2.license_expiry_date);

[User] Also only include pairs where the difference between their expiry dates is more than 30 days.

[Assistant]
SELECT d1.driver_id       AS driver_id,
       d1.first_name,
       d1.last_name,
       d2.driver_id       AS earlier_driver_id,
       d2.license_expiry_date AS earlier_expiry_date,
       DATE_PART('day', d1.license_expiry_date - d2.license_expiry_date) AS days_difference
FROM transportation.drivers d1
JOIN transportation.drivers d2
  ON d2.license_expiry_date < d1.license_expiry_date
     AND EXTRACT(YEAR FROM d1.license_expiry_date) = EXTRACT(YEAR FROM d2.license_expiry_date)
WHERE d1.license_expiry_date - d2.license_expiry_date > INTERVAL '30 days';

[User] For each customer, provide a summary of their account statuses, showing their full name, account status, and the count of accounts for each status.

[Assistant] SELECT c.first_name, c.last_name, a.status, COUNT(a.account_id) AS account_count FROM financial_services.accounts a JOIN financial_services.customers c ON a.customer_id = c.customer_id GROUP BY c.customer_id, c.first_name, c.last_name, a.status ORDER BY c.last_name, c.first_name, a.status;

[User] Refine this to only include customers who have accounts in at least two different statuses.

[Assistant] SELECT c.first_name, c.last_name, a.status, COUNT(a.account_id) AS account_count FROM financial_services.accounts a JOIN financial_services.customers c ON a.customer_id = c.customer_id GROUP BY c.customer_id, c.first_name, c.last_name, a.status HAVING c.customer_id IN ( SELECT customer_id FROM financial_services.accounts GROUP BY customer_id HAVING COUNT(DISTINCT status) >= 2 ) ORDER BY c.last_name, c.first_name, a.status;

[User] How many unique users have a KYC audit record with status 'pending'?

[Assistant]
SELECT COUNT(DISTINCT user_id) AS pending_kyc_users
FROM trading_platform.kyc_audit
WHERE status = 'pending';

[User] Retrieve the first and last names of all doctors who specialize in Cardiology.

[Assistant]
SELECT first_name, last_name
FROM healthcare.doctors
WHERE specialty = 'Cardiology';


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 )
##Table Structure
CREATE TABLE blockchain.transactions ( transaction_id.text, block_id.text, sender_address.text, receiver_address.text, amount.numeric, timestamp.timestamp, signature.text )
CREATE TABLE blockchain.addresses ( address_id.text, public_key.text, balance.numeric )
CREATE TABLE blockchain.nodes (
    node_id character varying(64) NOT NULL,  -- unique identifier for the node
    ip_address character varying(15) NOT NULL, -- IP address of the node
    port integer NOT NULL, -- port number of the node
    last_seen timestamp NOT NULL, -- last time the node was active
    PRIMARY KEY (node_id)
)
##Table Structure
CREATE TABLE transportation.trips (
    trip_id character varying(64) NOT NULL,  -- unique identifier for a specific trip instance
    route_id character varying(64), -- identifier of the route being followed (can be null for ad-hoc trips)
    vehicle_id character varying(64) NOT NULL, -- identifier of the vehicle used
    driver_id character varying(64) NOT NULL, -- identifier of the driver operating
    scheduled_departure timestamp with time zone NOT NULL, -- planned departure time
    actual_departure timestamp with time zone, -- actual departure time
    scheduled_arrival timestamp with time zone NOT NULL, -- planned arrival time
    actual_arrival timestamp with time zone, -- actual arrival time
    origin_location_id character varying(64) NOT NULL, -- actual starting location (could differ from route origin)
    destination_location_id character varying(64) NOT NULL, -- actual ending location (could differ from route destination)
    status character varying(32) NOT NULL, -- e.g., Scheduled, In Progress, Completed, Delayed, Cancelled
    passenger_count integer, -- number of passengers (if applicable)
    cargo_manifest_id character varying(64), -- link to cargo details (if applicable)
    PRIMARY KEY (trip_id)
)
##Table Structure
CREATE TABLE legal_services.clients ( client_id text PRIMARY KEY, first_name text, last_name text, company_name text, email text UNIQUE, phone text, address text, date_registered timestamp, status text )
##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.text, agency_name.text, jurisdiction_level.text, primary_contact_email.text, main_phone_number.text, website_url.text, established_date.date, parent_agency_id.text )
CREATE TABLE government_services.applications ( application_id.text, 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.documents ( document_id.text, application_id.text, citizen_id.text, document_type.text, file_reference.text, upload_timestamp.timestamp, expiry_date.date, verification_status.text, verified_by_employee_id.text, verification_timestamp.timestamp )
CREATE TABLE government_services.payments ( payment_id.text, application_id.text, citizen_id.text, service_id.text, amount.numeric, currency.text, payment_method.text, payment_provider_reference.text, payment_timestamp.timestamp, status.text, notes.text )
CREATE TABLE government_services.employees ( employee_id.text, agency_id.text, first_name.text, last_name.text, job_title.text, department.text, work_email.text, work_phone.text, hire_date.date, termination_date.date, access_level.text, manager_employee_id.text )
CREATE TABLE government_services.service_locations ( location_id.text, agency_id.text, location_name.text, address.text, city.text, state.text, postal_code.text, latitude.numeric, longitude.numeric, operating_hours.text, contact_phone.text, is_accessible.boolean )
CREATE TABLE government_services.notifications ( notification_id.text, 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 )
##Table Structure
CREATE TABLE government_services.services ( service_id text PRIMARY KEY, agency_id text, service_name text, description text, category text, eligibility_criteria text, standard_fee numeric, average_processing_time_days int, is_active boolean, online_application_url text )

[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] Which nodes have not been seen in the last 24 hours?

[Assistant]
SELECT node_id, ip_address, port, last_seen
FROM blockchain.nodes
WHERE last_seen < now() - INTERVAL '24 hours';

[User] Can you also include how many hours ago each node was last seen?

[Assistant]
SELECT node_id, ip_address, port, last_seen,
  EXTRACT(EPOCH FROM (now() - last_seen)) / 3600 AS hours_since_last_seen
FROM blockchain.nodes
WHERE last_seen < now() - INTERVAL '24 hours';

[User] Now filter to only those seen more than 48 hours ago and order by hours_since_last_seen descending.

[Assistant]
SELECT node_id, ip_address, port, last_seen,
  EXTRACT(EPOCH FROM (now() - last_seen)) / 3600 AS hours_since_last_seen
FROM blockchain.nodes
WHERE now() - last_seen > INTERVAL '48 hours'
ORDER BY hours_since_last_seen DESC;

[User] For each trip, show the trip ID, vehicle ID, driver ID, and both the actual starting and ending location IDs.

[Assistant] SELECT trip_id, vehicle_id, driver_id, origin_location_id, destination_location_id FROM transportation.trips;

[User] I need a list of unique company names and the number of clients in each company.

[Assistant]
SELECT company_name, COUNT(*) AS client_count
FROM legal_services.clients
WHERE company_name IS NOT NULL
GROUP BY company_name;

[User] Only include companies where there are at least 2 clients.

[Assistant]
SELECT company_name, COUNT(*) AS client_count
FROM legal_services.clients
WHERE company_name IS NOT NULL
GROUP BY company_name
HAVING COUNT(*) >= 2;

[User] Also, show the email addresses of the clients in those companies.

[Assistant]
SELECT c.company_name, c.email
FROM legal_services.clients c
WHERE c.company_name IN (
  SELECT company_name
  FROM legal_services.clients
  WHERE company_name IS NOT NULL
  GROUP BY company_name
  HAVING COUNT(*) >= 2
)
ORDER BY c.company_name, c.email;

[User] Only show companies whose name contains the word 'Group'.

[Assistant]
SELECT c.company_name, c.email
FROM legal_services.clients c
WHERE c.company_name IN (
  SELECT company_name
  FROM legal_services.clients
  WHERE company_name IS NOT NULL AND company_name ILIKE '%Group%'
  GROUP BY company_name
  HAVING COUNT(*) >= 2
)
ORDER BY c.company_name, c.email;

[User] List the citizen ID, full name, and registration date for all unverified citizens who registered in the year 2022.

[Assistant] SELECT citizen_id, first_name, last_name, registration_date FROM government_services.citizens WHERE is_verified = FALSE AND EXTRACT(YEAR FROM registration_date) = 2022;

[User] Which agencies offer more than one type of service category? List the agency_id and the number of distinct categories they provide.

[Assistant] SELECT agency_id, COUNT(DISTINCT category) AS category_count FROM government_services.services GROUP BY agency_id HAVING COUNT(DISTINCT category) > 1;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement. ##Table Structure
CREATE TABLE transportation.vehicles ( vehicle_id text PRIMARY KEY, license_plate text, vin text, make text, model text, year int, type text, capacity int, fuel_type text, status text, depot_id text, acquisition_date date )
CREATE TABLE transportation.drivers ( driver_id text PRIMARY KEY, employee_id text, first_name text, last_name text, license_number text, license_expiry_date date, contact_number text, email text, hire_date date, status text )
CREATE TABLE transportation.routes ( route_id text 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.locations ( location_id text PRIMARY KEY, name text, type text, address_line1 text, city text, state_province text, postal_code text, country text, latitude numeric, longitude numeric, timezone text )
CREATE TABLE transportation.maintenance_logs ( log_id text PRIMARY KEY, vehicle_id text, service_date date, odometer_reading int, service_type text, description text, cost numeric, mechanic_name text, next_service_due_date date )
CREATE TABLE transportation.fuel_logs ( fuel_log_id text PRIMARY KEY, 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 int, location_id text )
CREATE TABLE transportation.passengers ( passenger_id text PRIMARY KEY, first_name text, last_name text, email text, phone_number text, date_of_birth date, loyalty_program_id text, created_at timestamp )
CREATE TABLE transportation.bookings ( booking_id text PRIMARY KEY, passenger_id text, trip_id text, seat_number text, booking_time timestamp, status text, fare numeric, payment_transaction_id text, special_requests text )
##Table Structure
CREATE TABLE transportation.vehicles ( vehicle_id text PRIMARY KEY, license_plate text, vin text, make text, model text, year int, type text, capacity int, fuel_type text, status text, depot_id text, acquisition_date date )
CREATE TABLE transportation.drivers ( driver_id.text, employee_id.text, first_name.text, last_name.text, license_number.text, license_expiry_date.date, contact_number.text, email.text, hire_date.date, status.text )
CREATE TABLE transportation.routes ( route_id text, route_number text, description text, origin_location_id text, destination_location_id text, distance_km numeric, estimated_duration_minutes integer, type text )
CREATE TABLE transportation.locations ( location_id text, name text, type text, address_line1 text, city text, state_province text, postal_code text, country text, latitude numeric, longitude numeric, timezone text )
CREATE TABLE transportation.maintenance_logs (
    log_id character varying(64) NOT NULL,  -- unique identifier for the maintenance record
    vehicle_id character varying(64) NOT NULL, -- identifier of the vehicle serviced
    service_date date NOT NULL, -- date the service was performed
    odometer_reading integer, -- vehicle mileage at time of service
    service_type character varying(128) NOT NULL, -- type of service (e.g., Oil Change, Tire Rotation, Engine Repair)
    description text NOT NULL, -- detailed description of work done
    cost numeric(10, 2), -- cost of the service
    mechanic_name character varying(128), -- name or ID of the mechanic/shop
    next_service_due_date date, -- recommended date for next service
    PRIMARY KEY (log_id)
)
CREATE TABLE transportation.passengers (
    passenger_id character varying(64) NOT NULL,  -- unique identifier for the passenger
    first_name character varying(128) NOT NULL, -- passenger's first name
    last_name character varying(128) NOT NULL, -- passenger's last name
    email character varying(128) UNIQUE, -- email address
    phone_number character varying(32) UNIQUE, -- phone number
    date_of_birth date, -- passenger's date of birth
    loyalty_program_id character varying(64), -- identifier for loyalty program membership
    created_at timestamp with time zone NOT NULL, -- time when the passenger record was created
    PRIMARY KEY (passenger_id)
)
CREATE TABLE transportation.bookings ( booking_id character varying(64) NOT NULL, passenger_id character varying(64) NOT NULL, trip_id character varying(64) NOT NULL, seat_number character varying(16), booking_time timestamp with time zone NOT NULL, status character varying(32) NOT NULL, fare numeric(10, 2) NOT NULL, payment_transaction_id character varying(128), special_requests text, PRIMARY KEY (booking_id) )
##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)
)
CREATE TABLE insurance.policy_beneficiaries (
    beneficiary_id character varying(64) NOT NULL, -- unique identifier for the beneficiary entry
    policy_id character varying(64) NOT NULL, -- identifier of the life/relevant policy (FK to policies)
    customer_id character varying(64) NOT NULL, -- identifier of the beneficiary (could be FK to customers or store info directly)
    first_name character varying(100) NOT NULL, -- beneficiary first name (if not linking to customers table)
    last_name character varying(100) NOT NULL, -- beneficiary last name
    relationship character varying(50) NOT NULL, -- relationship to the policyholder (e.g., Spouse, Child, Parent)
    percentage_share numeric(5, 2) NOT NULL CHECK (percentage_share > 0 AND percentage_share <= 100), -- percentage of payout
    contact_info text, -- contact details for the beneficiary
    added_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
    PRIMARY KEY (beneficiary_id),
    UNIQUE (policy_id, customer_id) -- Ensure a person is listed only once per policy
)
##Table Structure
CREATE TABLE social_media.post_hashtags ( post_hashtag_id character varying(64) NOT NULL, post_id character varying(64) NOT NULL, hashtag_id character varying(64) NOT NULL, PRIMARY KEY (post_hashtag_id), CONSTRAINT unique_post_hashtag UNIQUE (post_id, hashtag_id) )

[User] Show the full name and email of each driver and the number of vehicles currently assigned to their depot.

[Assistant]
SELECT d.first_name, d.last_name, d.email, COUNT(v.vehicle_id) AS vehicles_at_depot
FROM transportation.drivers d
JOIN transportation.vehicles v ON d.driver_id = v.vehicle_id
JOIN transportation.locations l ON v.depot_id = l.location_id
GROUP BY d.driver_id, d.first_name, d.last_name, d.email;

[User] I think the join is incorrect—drivers don’t have vehicle_id. Can you instead count all vehicles per depot and show each driver's full name, email, and the count for their assigned depot, assuming drivers and vehicles share depot assignments by depot_id?

[Assistant]
SELECT d.first_name, d.last_name, d.email, COUNT(v.vehicle_id) AS vehicles_at_depot
FROM transportation.drivers d
JOIN transportation.vehicles v ON d.status = 'Active' AND d.driver_id IS NOT NULL AND v.depot_id = (
    SELECT v2.depot_id FROM transportation.vehicles v2 WHERE v2.vehicle_id = v.vehicle_id LIMIT 1
)
GROUP BY d.driver_id, d.first_name, d.last_name, d.email;

[User] List all drivers along with the make and model of each vehicle they have been assigned to for trips.

[Assistant]
SELECT DISTINCT d.driver_id, d.first_name || ' ' || d.last_name AS driver_full_name, v.make, v.model
FROM transportation.drivers d
JOIN transportation.trips t ON d.driver_id = t.driver_id
JOIN transportation.vehicles v ON t.vehicle_id = v.vehicle_id;

[User] What is the average estimated_loss for each claim status?

[Assistant]
SELECT status, AVG(estimated_loss) AS avg_estimated_loss
FROM insurance.claims
GROUP BY status;

[User] How many unique hashtags are linked to each post? Return post_id and hashtag_count.

[Assistant]
SELECT post_id, COUNT(DISTINCT hashtag_id) AS hashtag_count
FROM social_media.post_hashtags
GROUP BY post_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 financial_services.transactions ( transaction_id text, account_id text, related_account_id text, transaction_type text, amount numeric, currency text, transaction_date timestamp, effective_date date, description text, status text, reference_number text )
CREATE TABLE financial_services.securities ( security_id text, ticker_symbol text, isin_code text, cusip_code text, security_name text, security_type text, exchange text, currency text, issuer_name text, sector text, last_updated timestamp )
CREATE TABLE financial_services.market_data ( data_point_id bigint, security_id text, data_timestamp timestamp, open_price numeric, high_price numeric, low_price numeric, close_price numeric, adjusted_close_price numeric, volume bigint, source text )
##Table Structure
CREATE TABLE gaming_technology.players ( player_id.uuid, username.text, email.text, password_hash.text, registration_date.timestamptz, last_login.timestamptz, country_code.text, status.text, profile_data.jsonb )
##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)
)
##Table Structure
CREATE TABLE financial_services.accounts ( account_id.text, customer_id.text, account_number.text, account_type.text, balance.numeric, currency.text, opened_date.date, status.text, interest_rate.numeric, last_updated_at.timestamp )
##Table Structure
CREATE TABLE social_media.post_hashtags ( post_hashtag_id text, post_id text, hashtag_id text )
CREATE TABLE social_media.conversation_participants ( participant_id text, conversation_id text, user_id text, joined_at timestamp, last_read_at timestamp )
##Table Structure
CREATE TABLE smart_money_token_inflow ( token_address character varying(100) NOT NULL, -- the token's address token_symbol character varying(100), -- the tokens's symbol token_amount numeric(38,2), -- the absolute value of the amount if user bought minus  the amount user sold of this token usd_value numeric(38,2), -- the absolute usd value of the bought token minus sold token avg_price numeric(38,6), -- the average cost price of user spent on this token type int, -- the direction of the trade on this token. 1 means buying, 2 means selling address_amount integer, -- the amount of the user bought this token narrative character varying(100), -- the category or narrative of the token chain character varying(100), -- the chain that the token resides ,PRIMARY KEY (token_address, chain) )

[User] Show the total number of transactions for each currency.

[Assistant] SELECT currency, COUNT(*) FROM financial_services.transactions GROUP BY currency

[User] Can you also include the total amount for each currency?

[Assistant] SELECT currency, COUNT(*), SUM(amount) FROM financial_services.transactions GROUP BY currency

[User] Can you give me the count of players grouped by their status?

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

[User] Actually, include the percentage of total players for each status.

[Assistant]
SELECT status,
       COUNT(*) AS player_count,
       ROUND(100.0 * COUNT(*) / SUM(COUNT(*)) OVER (), 2) AS percentage
FROM gaming_technology.players
GROUP BY status;

[User] Only show statuses where this percentage is over 10%.

[Assistant]
WITH counts AS (
  SELECT status,
         COUNT(*) AS player_count,
         ROUND(100.0 * COUNT(*) / SUM(COUNT(*)) OVER (), 2) AS percentage
  FROM gaming_technology.players
  GROUP BY status
)
SELECT *
FROM counts
WHERE percentage > 10;

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

[Assistant]
WITH counts AS (
  SELECT status,
         COUNT(*) AS player_count,
         ROUND(100.0 * COUNT(*) / SUM(COUNT(*)) OVER (), 2) AS percentage
  FROM gaming_technology.players
  GROUP BY status
)
SELECT *
FROM counts
WHERE percentage > 10
ORDER BY percentage DESC;

[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] Show each customer's checking and savings account numbers for customers who have both types.

[Assistant]
SELECT a.customer_id,
       a.account_number AS checking_account,
       b.account_number AS savings_account
FROM financial_services.accounts a
JOIN financial_services.accounts b
  ON a.customer_id = b.customer_id
  AND a.account_type = 'Checking'
  AND b.account_type = 'Savings';

[User] Also include the opened_date for both checking and savings accounts.

[Assistant]
SELECT a.customer_id,
       a.account_number AS checking_account,
       a.opened_date  AS checking_opened,
       b.account_number AS savings_account,
       b.opened_date  AS savings_opened
FROM financial_services.accounts a
JOIN financial_services.accounts b
  ON a.customer_id = b.customer_id
  AND a.account_type = 'Checking'
  AND b.account_type = 'Savings';

[User] Only include customers where both accounts have status 'Active'.

[Assistant]
SELECT a.customer_id,
       a.account_number AS checking_account,
       a.opened_date  AS checking_opened,
       b.account_number AS savings_account,
       b.opened_date  AS savings_opened
FROM financial_services.accounts a
JOIN financial_services.accounts b
  ON a.customer_id = b.customer_id
  AND a.account_type = 'Checking'
  AND b.account_type = 'Savings'
WHERE a.status = 'Active'
  AND b.status = 'Active';

[User] Show me the user_id and number of conversations they have joined. Only include users who joined more than one conversation.

[Assistant]
SELECT user_id, COUNT(DISTINCT conversation_id) AS conversations_joined
FROM social_media.conversation_participants
GROUP BY user_id
HAVING COUNT(DISTINCT conversation_id) > 1;

[User] Add the time they joined their most recent conversation as latest_joined_at.

[Assistant]
SELECT user_id, COUNT(DISTINCT conversation_id) AS conversations_joined, MAX(joined_at) AS latest_joined_at
FROM social_media.conversation_participants
GROUP BY user_id
HAVING COUNT(DISTINCT conversation_id) > 1;

[User] Also, show the IDs of the conversations for each user as a comma-separated list.

[Assistant]
SELECT user_id,
  COUNT(DISTINCT conversation_id) AS conversations_joined,
  MAX(joined_at) AS latest_joined_at,
  STRING_AGG(DISTINCT conversation_id, ',') AS conversation_ids
FROM social_media.conversation_participants
GROUP BY user_id
HAVING COUNT(DISTINCT conversation_id) > 1;

[User] Which narrative had the highest total USD token inflow during Q1 of 2024, and which chain did these inflows primarily occur on?

[Assistant] SELECT narrative, chain, SUM(usd_value) AS total_inflow FROM smart_money_token_inflow WHERE type = 1 AND EXTRACT(YEAR FROM CURRENT_DATE) = 2024 AND EXTRACT(MONTH FROM CURRENT_DATE) BETWEEN 1 AND 3 GROUP BY narrative, chain ORDER BY total_inflow DESC LIMIT 1;

[User] Could you modify the query to show the top 3 narratives by total inflow, along with their corresponding chains?

[Assistant] SELECT narrative, chain, SUM(usd_value) AS total_inflow FROM smart_money_token_inflow WHERE type = 1 AND EXTRACT(YEAR FROM CURRENT_DATE) = 2024 AND EXTRACT(MONTH FROM CURRENT_DATE) BETWEEN 1 AND 3 GROUP BY narrative, chain ORDER BY total_inflow DESC LIMIT 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 hospitality_technology.properties (
    property_id character varying(64) NOT NULL,  -- unique identifier for the property (hotel, resort, etc.)
    property_name character varying(255) NOT NULL, -- name of the property
    address_line1 character varying(255) NOT NULL, -- primary address line
    address_line2 character varying(255), -- secondary address line
    city character varying(100) NOT NULL, -- city
    state_province character varying(100), -- state or province
    postal_code character varying(20) NOT NULL, -- zip or postal code
    country_code character varying(3) NOT NULL, -- ISO country code (e.g., USA, CAN)
    phone_number character varying(30), -- main contact phone
    email_address character varying(255), -- main contact email
    property_type character varying(50) NOT NULL, -- e.g., Hotel, Resort, B&B, Motel
    star_rating numeric(2,1), -- star rating (e.g., 4.5)
    timezone character varying(64) NOT NULL, -- IANA timezone ID (e.g., America/New_York)
    manager_staff_id character varying(64), -- FK to staff table for the general manager
    created_at timestamp with time zone NOT NULL DEFAULT current_timestamp, -- record creation time
    updated_at timestamp with time zone NOT NULL DEFAULT current_timestamp, -- record last update time
    PRIMARY KEY (property_id)
)
CREATE TABLE hospitality_technology.staff ( staff_id text PRIMARY KEY, property_id text, first_name text, last_name text, position text, work_email text, work_phone text, hire_date date, termination_date date, is_active boolean, access_level int, manager_id text, created_at timestamp )
CREATE TABLE hospitality_technology.service_orders ( order_id text PRIMARY KEY, reservation_id text, guest_id text, service_id text, staff_id_ordered text, staff_id_delivered text, order_timestamp timestamp, delivery_timestamp timestamp, quantity int, unit_price numeric, total_price numeric, status text, notes text, bill_id text )
CREATE TABLE hospitality_technology.reviews ( review_id text, property_id text, reservation_id text, guest_id text, rating_overall integer, rating_cleanliness integer, rating_service integer, rating_location integer, rating_value integer, comment text, review_source text, review_date timestamp, is_public boolean, staff_response text, response_staff_id text, response_date timestamp )
##Table Structure
CREATE TABLE legal_services.clients ( client_id character varying(64) NOT NULL, first_name character varying(100) NOT NULL, last_name character varying(100) NOT NULL, company_name character varying(200), email character varying(128) UNIQUE NOT NULL, phone character varying(32), address text, date_registered timestamp NOT NULL, status character varying(32) NOT NULL, PRIMARY KEY (client_id) )
CREATE TABLE legal_services.lawyers ( lawyer_id character varying(64) NOT NULL, first_name character varying(100) NOT NULL, last_name character varying(100) NOT NULL, bar_number character varying(64) UNIQUE NOT NULL, firm_id character varying(64), email character varying(128) UNIQUE NOT NULL, phone character varying(32), specialization text, hire_date timestamp NOT NULL, is_partner boolean DEFAULT false, PRIMARY KEY (lawyer_id) )
CREATE TABLE legal_services.law_firms ( firm_id character varying(64) NOT NULL, firm_name character varying(200) NOT NULL, address text NOT NULL, phone character varying(32), website character varying(255), founded_date date, managing_partner_id character varying(64), PRIMARY KEY (firm_id) )
CREATE TABLE legal_services.cases ( case_id character varying(64) NOT NULL, case_number character varying(100) UNIQUE, case_name text NOT NULL, client_id character varying(64) NOT NULL, lead_lawyer_id character varying(64) NOT NULL, case_type character varying(100) NOT NULL, status character varying(50) NOT NULL, date_opened timestamp NOT NULL, date_closed timestamp, description text, court_jurisdiction character varying(128), PRIMARY KEY (case_id) )
CREATE TABLE legal_services.documents ( document_id character varying(64) NOT NULL, case_id character varying(64) NOT NULL, document_name character varying(255) NOT NULL, document_type character varying(100), storage_path text NOT NULL, uploaded_by_lawyer_id character varying(64), upload_timestamp timestamp NOT NULL, version integer DEFAULT 1, description text, PRIMARY KEY (document_id) )
CREATE TABLE legal_services.time_entries ( entry_id character varying(64) NOT NULL, case_id character varying(64) NOT NULL, lawyer_id character varying(64) NOT NULL, date_worked date NOT NULL, hours_spent numeric(5, 2) NOT NULL CHECK (hours_spent > 0), billing_rate numeric(10, 2) NOT NULL, description text NOT NULL, is_billable boolean DEFAULT true, is_billed boolean DEFAULT false, invoice_id character varying(64), created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, PRIMARY KEY (entry_id) )
CREATE TABLE legal_services.appointments ( appointment_id character varying(64) NOT NULL, client_id character varying(64) NOT NULL, lawyer_id character varying(64) NOT NULL, case_id character varying(64), start_time timestamp NOT NULL, end_time timestamp NOT NULL, location text, subject character varying(255), notes text, status character varying(50) NOT NULL, created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, PRIMARY KEY (appointment_id) )
##Table Structure
CREATE TABLE gaming_technology.player_inventory (
    inventory_id uuid NOT NULL DEFAULT gen_random_uuid(), -- unique identifier for an inventory entry
    player_id uuid NOT NULL, -- FK linking to the player owning the item
    item_id uuid NOT NULL, -- FK linking to the item definition
    quantity integer NOT NULL DEFAULT 1, -- number of items held (for stackable items)
    acquired_at timestamp with time zone NOT NULL DEFAULT CURRENT_TIMESTAMP, -- when the item was acquired
    instance_data jsonb, -- data specific to this instance (e.g., weapon mods, durability)
    PRIMARY KEY (inventory_id),
    -- Optional unique constraint if items are non-stackable or unique instances
    -- UNIQUE (player_id, item_id) -- Use if quantity is always 1
    -- FOREIGN KEY (player_id) REFERENCES gaming_technology.players(player_id),
    -- FOREIGN KEY (item_id) REFERENCES gaming_technology.in_game_items(item_id)
)
##Table Structure
CREATE TABLE legal_services.cases ( case_id.text, case_number.text, case_name.text, client_id.text, lead_lawyer_id.text, case_type.text, status.text, date_opened.timestamp, date_closed.timestamp, description.text, court_jurisdiction.text )

[User] List all public reviews from the past 30 days with the property name and overall rating.

[Assistant]
SELECT r.review_id, p.property_name, r.rating_overall, r.review_date
FROM hospitality_technology.reviews AS r
JOIN hospitality_technology.properties AS p
  ON r.property_id = p.property_id
WHERE r.is_public = TRUE
  AND r.review_date >= CURRENT_DATE - INTERVAL '30 days';

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

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

[User] Show the latest time each player acquired any item.

[Assistant] SELECT player_id, MAX(acquired_at) AS last_acquired_at FROM gaming_technology.player_inventory GROUP BY player_id;

[User] Actually, can you also show the total number of items that each player acquired?

[Assistant] SELECT player_id, MAX(acquired_at) AS last_acquired_at, SUM(quantity) AS total_items_acquired FROM gaming_technology.player_inventory GROUP BY player_id;

[User] I would also like this ordered by total_items_acquired descending.

[Assistant] SELECT player_id, MAX(acquired_at) AS last_acquired_at, SUM(quantity) AS total_items_acquired FROM gaming_technology.player_inventory GROUP BY player_id ORDER BY total_items_acquired DESC;

[User] Find pairs of cases that share the same client and have the same status, but are different cases. Display the case name and case number for both cases in the pair, along with the shared client ID and shared status.

[Assistant] SELECT T1.case_name, T1.case_number, T2.case_name, T2.case_number, T1.client_id, T1.status FROM legal_services.cases AS T1 JOIN legal_services.cases AS T2 ON T1.client_id = T2.client_id AND T1.status = T2.status WHERE T1.case_id < T2.case_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 transportation.routes ( route_id text, route_number text, description text, origin_location_id text, destination_location_id text, distance_km numeric, estimated_duration_minutes integer, type text )
CREATE TABLE transportation.trips ( trip_id text, route_id text, vehicle_id text, driver_id text, scheduled_departure timestamp, actual_departure timestamp, scheduled_arrival timestamp, actual_arrival timestamp, origin_location_id text, destination_location_id text, status text, passenger_count integer, cargo_manifest_id text )
CREATE TABLE transportation.fuel_logs ( fuel_log_id text, vehicle_id text, trip_id text, log_timestamp timestamp, fuel_type text, quantity numeric, unit text, cost_per_unit numeric, total_cost numeric, odometer_reading integer, location_id text )
##Table Structure
CREATE TABLE hospitality_technology.services ( service_id.text, property_id.text, service_name.text, description.text, category.text, price.numeric, unit.text, is_available.boolean, department.text )
##Table Structure
CREATE TABLE legal_services.invoices (
    invoice_id character varying(64) NOT NULL,  -- unique identifier for the invoice
    invoice_number character varying(100) UNIQUE NOT NULL, -- user-facing invoice number
    client_id character varying(64) NOT NULL, -- FK to clients table
    case_id character varying(64), -- FK to cases table (optional, could be general retainer)
    issue_date date NOT NULL, -- date the invoice was generated
    due_date date NOT NULL, -- date the payment is due
    total_amount numeric(12, 2) NOT NULL, -- total amount due on the invoice
    amount_paid numeric(12, 2) DEFAULT 0.00, -- amount already paid
    status character varying(50) NOT NULL, -- e.g., Draft, Sent, Paid, Partially Paid, Overdue, Void
    payment_date timestamp, -- date the invoice was fully paid (nullable)
    notes text, -- additional notes or terms on the invoice
    created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
    PRIMARY KEY (invoice_id)
)
##Table Structure
CREATE TABLE social_media.conversation_participants ( participant_id text, conversation_id text, user_id text, joined_at timestamp, last_read_at timestamp )
##Table Structure
CREATE TABLE healthcare.diagnoses (
    diagnosis_id character varying(64) NOT NULL, -- unique identifier for the diagnosis entry
    record_id character varying(64) NOT NULL, -- FK linking to the specific medical record entry
    patient_id character varying(64) NOT NULL, -- FK to patients table
    doctor_id character varying(64) NOT NULL, -- FK to doctors table (diagnosing doctor)
    diagnosis_code character varying(20) NOT NULL, -- standard code (e.g., ICD-10)
    code_type character varying(10) NOT NULL DEFAULT 'ICD-10', -- type of code used
    description text, -- textual description of the diagnosis
    diagnosis_date date NOT NULL, -- date the diagnosis was made
    status character varying(32) NOT NULL, -- e.g., Active, Resolved, Ruled Out
    is_chronic boolean DEFAULT false, -- flag for chronic conditions
    PRIMARY KEY (diagnosis_id)
)
##Table Structure
CREATE TABLE gaming_technology.game_sessions ( session_id uuid, player_id uuid, game_id uuid, server_id uuid, start_time timestamp with time zone, end_time timestamp with time zone, duration_seconds integer, score integer, session_data jsonb )

[User] How many trips used more than 500 units of fuel, and what are their trip IDs and scheduled departure times?

[Assistant]
SELECT t.trip_id, t.scheduled_departure, SUM(f.quantity) AS total_fuel
FROM transportation.trips t
JOIN transportation.fuel_logs f ON t.trip_id = f.trip_id
GROUP BY t.trip_id, t.scheduled_departure
HAVING SUM(f.quantity) > 500;

[User] Change the query to show the route number for these trips as well.

[Assistant]
SELECT t.trip_id, t.scheduled_departure, r.route_number, SUM(f.quantity) AS total_fuel
FROM transportation.trips t
JOIN transportation.routes r ON t.route_id = r.route_id
JOIN transportation.fuel_logs f ON t.trip_id = f.trip_id
GROUP BY t.trip_id, t.scheduled_departure, r.route_number
HAVING SUM(f.quantity) > 500;

[User] Show me all services grouped by category, including the minimum and maximum price in each category, and the total number of services.

[Assistant] SELECT category, MIN(price) AS min_price, MAX(price) AS max_price, COUNT(*) AS service_count FROM hospitality_technology.services GROUP BY category;

[User] Please only include categories with more than 3 services.

[Assistant] SELECT category, MIN(price) AS min_price, MAX(price) AS max_price, COUNT(*) AS service_count FROM hospitality_technology.services GROUP BY category HAVING COUNT(*) > 3;

[User] Actually, sort the results by service_count descending and show the category first.

[Assistant] SELECT category, COUNT(*) AS service_count, MIN(price) AS min_price, MAX(price) AS max_price FROM hospitality_technology.services GROUP BY category HAVING COUNT(*) > 3 ORDER BY service_count DESC;

[User] Show me the total invoice amount and the number of invoices for each client in 2024, and include the earliest and latest invoice issue date for each client.

[Assistant]
SELECT client_id, SUM(total_amount) AS total_invoice_amount, COUNT(*) AS invoice_count, MIN(issue_date) AS earliest_issue_date, MAX(issue_date) AS latest_issue_date
FROM legal_services.invoices
WHERE EXTRACT(YEAR FROM issue_date) = 2024
GROUP BY client_id;

[User] List all pairs of users who participated in the same conversation. For each, show conversation_id, user_id1, user_id2.

[Assistant]
SELECT p1.conversation_id,
       p1.user_id AS user_id1,
       p2.user_id AS user_id2
FROM social_media.conversation_participants p1
JOIN social_media.conversation_participants p2
  ON p1.conversation_id = p2.conversation_id
WHERE p1.user_id < p2.user_id;

[User] Only include pairs where both joined after '2024-06-01'.

[Assistant]
SELECT p1.conversation_id,
       p1.user_id AS user_id1,
       p2.user_id AS user_id2
FROM social_media.conversation_participants p1
JOIN social_media.conversation_participants p2
  ON p1.conversation_id = p2.conversation_id
WHERE p1.user_id < p2.user_id
  AND p1.joined_at > '2024-06-01'
  AND p2.joined_at > '2024-06-01';

[User] List all pairs of diagnoses that belong to the same medical record. Show record_id, diagnosis_id from the first entry as diag1_id, and diagnosis_id from the second entry as diag2_id.

[Assistant]
SELECT d1.record_id,
       d1.diagnosis_id AS diag1_id,
       d2.diagnosis_id AS diag2_id
FROM healthcare.diagnoses d1
JOIN healthcare.diagnoses d2
  ON d1.record_id = d2.record_id
 AND d1.diagnosis_id < d2.diagnosis_id;

[User] Only include pairs where both diagnoses are chronic.

[Assistant]
SELECT d1.record_id,
       d1.diagnosis_id AS diag1_id,
       d2.diagnosis_id AS diag2_id
FROM healthcare.diagnoses d1
JOIN healthcare.diagnoses d2
  ON d1.record_id = d2.record_id
 AND d1.diagnosis_id < d2.diagnosis_id
WHERE d1.is_chronic = TRUE
  AND d2.is_chronic = TRUE;

[User] What is the highest score achieved in any session for each player on each game?

[Assistant] SELECT player_id, game_id, MAX(score) AS highest_score FROM gaming_technology.game_sessions GROUP BY player_id, game_id;

[User] Show only the player/game combinations where the highest score is at least 500.

[Assistant] SELECT player_id, game_id, MAX(score) AS highest_score FROM gaming_technology.game_sessions GROUP BY player_id, game_id HAVING MAX(score) >= 500;

[User] Also include the number of sessions for each player/game pair.

[Assistant] SELECT player_id, game_id, MAX(score) AS highest_score, COUNT(*) AS session_count FROM gaming_technology.game_sessions GROUP BY player_id, game_id HAVING MAX(score) >= 500;