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.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 )
CREATE TABLE financial_services.employees ( employee_id text, first_name text, last_name text, job_title text, department text, branch_id text, email text, phone_extension text, hire_date date, termination_date date, manager_id text, status text )
##Table Structure
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.services ( service_id.text, agency_id.text, service_name.text, description.text, category.text, eligibility_criteria.text, standard_fee.numeric, average_processing_time_days.integer, is_active.boolean, online_application_url.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.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 transportation.vehicles ( vehicle_id.text, license_plate.text, vin.text, make.text, model.text, year.integer, type.text, capacity.integer, fuel_type.text, status.text, depot_id.text, acquisition_date.date )
CREATE TABLE transportation.drivers ( driver_id.text, employee_id.text, first_name.text, last_name.text, license_number.text, license_expiry_date.date, contact_number.text, email.text, hire_date.date, status.text )
CREATE TABLE transportation.routes ( route_id.text, route_number.text, description.text, origin_location_id.text, destination_location_id.text, distance_km.numeric, estimated_duration_minutes.integer, type.text )
CREATE TABLE transportation.trips ( trip_id.text, route_id.text, vehicle_id.text, driver_id.text, scheduled_departure.timestamp, actual_departure.timestamp, scheduled_arrival.timestamp, actual_arrival.timestamp, origin_location_id.text, destination_location_id.text, status.text, passenger_count.integer, cargo_manifest_id.text )
CREATE TABLE transportation.fuel_logs ( fuel_log_id.text, vehicle_id.text, trip_id.text, log_timestamp.timestamp, fuel_type.text, quantity.numeric, unit.text, cost_per_unit.numeric, total_cost.numeric, odometer_reading.integer, location_id.text )
CREATE TABLE transportation.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 insurance.policies ( policy_id character varying(64) NOT NULL, customer_id character varying(64) NOT NULL, product_id character varying(64) NOT NULL, agent_id character varying(64), policy_number character varying(100) NOT NULL UNIQUE, start_date date NOT NULL, end_date date NOT NULL, premium_amount numeric(12, 2) NOT NULL, coverage_limit numeric(15, 2) NOT NULL, deductible numeric(10, 2) NOT NULL, status character varying(30) NOT NULL, issued_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, cancellation_date date, cancellation_reason text, PRIMARY KEY (policy_id) )
##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 )

[User] For each employee who acts as a manager, please show the number of employees directly reporting to them.

[Assistant] SELECT m.first_name || ' ' || m.last_name AS manager_name, COUNT(e.employee_id) AS direct_report_count FROM financial_services.employees AS e JOIN financial_services.employees AS m ON e.manager_id = m.employee_id GROUP BY m.employee_id, manager_name;

[User] Include the department of the manager in the output as well.

[Assistant] SELECT m.first_name || ' ' || m.last_name AS manager_name, m.department, COUNT(e.employee_id) AS direct_report_count FROM financial_services.employees AS e JOIN financial_services.employees AS m ON e.manager_id = m.employee_id GROUP BY m.employee_id, manager_name, m.department;

[User] Only list managers who have fewer than 10 direct reports.

[Assistant] SELECT m.first_name || ' ' || m.last_name AS manager_name, m.department, COUNT(e.employee_id) AS direct_report_count FROM financial_services.employees AS e JOIN financial_services.employees AS m ON e.manager_id = m.employee_id GROUP BY m.employee_id, manager_name, m.department HAVING COUNT(e.employee_id) < 10;

[User] Get appointment_id, scheduled_start_time, service_name, location_name, and city for all appointments booked via 'Phone' at accessible locations.

[Assistant] SELECT ap.appointment_id, ap.scheduled_start_time, s.service_name, sl.location_name, sl.city FROM government_services.appointments ap JOIN government_services.services s ON s.service_id = ap.service_id JOIN government_services.service_locations sl ON sl.location_id = ap.location_id WHERE ap.booking_method = 'Phone' AND sl.is_accessible = TRUE;

[User] For each trip that has associated bookings, show the trip ID, the total number of passengers recorded for the trip, and the total fare collected from all bookings for that trip.

[Assistant] SELECT T1.trip_id, T1.passenger_count, SUM(T2.fare) FROM transportation.trips AS T1 JOIN transportation.bookings AS T2 ON T1.trip_id = T2.trip_id GROUP BY T1.trip_id, T1.passenger_count;

[User] List all replacement policies where a customer received a new policy starting the day after their previous policy was cancelled. Return customer_id, original_policy_id, original_cancellation_date, new_policy_id, new_start_date.

[Assistant]
SELECT orig.customer_id,
       orig.policy_id      AS original_policy_id,
       orig.cancellation_date AS original_cancellation_date,
       nw.policy_id        AS new_policy_id,
       nw.start_date       AS new_start_date
FROM insurance.policies orig
JOIN insurance.policies nw
  ON orig.customer_id = nw.customer_id
 AND orig.cancellation_date IS NOT NULL
 AND nw.start_date = orig.cancellation_date + INTERVAL '1 day';

[User] Now include the premium_amount difference as premium_diff and only show cases where the new policy's premium is higher.

[Assistant]
SELECT orig.customer_id,
       orig.policy_id      AS original_policy_id,
       orig.cancellation_date AS original_cancellation_date,
       nw.policy_id        AS new_policy_id,
       nw.start_date       AS new_start_date,
       (nw.premium_amount - orig.premium_amount) AS premium_diff
FROM insurance.policies orig
JOIN insurance.policies nw
  ON orig.customer_id = nw.customer_id
 AND orig.cancellation_date IS NOT NULL
 AND nw.start_date = orig.cancellation_date + INTERVAL '1 day'
WHERE nw.premium_amount > orig.premium_amount;

[User] Show me a list of all customers from California along with their full names and phone numbers.

[Assistant] SELECT customer_id, first_name || ' ' || last_name AS full_name, phone_number FROM insurance.customers WHERE state = 'CA';

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

[Assistant] SELECT customer_id, first_name || ' ' || last_name AS full_name, phone_number, email FROM insurance.customers WHERE state = 'CA';

[User] Actually, show me only those customers whose status is 'active'.

[Assistant] SELECT customer_id, first_name || ' ' || last_name AS full_name, phone_number, email FROM insurance.customers WHERE state = 'CA' AND status = 'active';


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement. ##Table Structure
CREATE TABLE social_media.users (
    user_id character varying(64) NOT NULL,  -- unique identifier for the user
    username character varying(50) NOT NULL UNIQUE, -- user's unique handle
    email character varying(128) NOT NULL UNIQUE, -- user's email address
    password_hash text NOT NULL, -- hashed password
    full_name character varying(100), -- user's full name
    profile_picture_url text, -- URL to the profile picture
    bio text, -- short user biography
    location character varying(100), -- user's location
    created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, -- timestamp of account creation
    updated_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, -- timestamp of last profile update
    is_verified boolean NOT NULL DEFAULT false, -- verification status
    PRIMARY KEY (user_id)
)
CREATE TABLE social_media.posts (
    post_id character varying(64) NOT NULL, -- unique identifier for the post
    user_id character varying(64) NOT NULL, -- identifier of the user who created the post (FK to users.user_id)
    content text, -- textual content of the post
    media_url text, -- URL to attached media (image/video)
    media_type character varying(20), -- type of media ('image', 'video', null)
    created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, -- timestamp of post creation
    updated_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, -- timestamp of last post edit
    visibility character varying(20) NOT NULL DEFAULT 'public', -- visibility ('public', 'friends', 'private')
    location_lat numeric(9,6), -- latitude of post location
    location_lon numeric(9,6), -- longitude of post location
    PRIMARY KEY (post_id)
)
CREATE TABLE social_media.likes (
    like_id character varying(64) NOT NULL, -- unique identifier for the like
    user_id character varying(64) NOT NULL, -- identifier of the user who liked (FK to users.user_id)
    post_id character varying(64), -- identifier of the post being liked (FK to posts.post_id, nullable)
    comment_id character varying(64), -- identifier of the comment being liked (FK to comments.comment_id, nullable)
    created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, -- timestamp of when the like occurred
    PRIMARY KEY (like_id),
    CONSTRAINT unique_user_like UNIQUE (user_id, post_id, comment_id), -- prevent duplicate likes
    CONSTRAINT check_like_target CHECK (post_id IS NOT NULL OR comment_id IS NOT NULL) -- ensure it likes something
)
CREATE TABLE social_media.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.post_hashtags (
    post_hashtag_id character varying(64) NOT NULL, -- unique identifier for the post-hashtag link
    post_id character varying(64) NOT NULL, -- identifier of the post (FK to posts.post_id)
    hashtag_id character varying(64) NOT NULL, -- identifier of the hashtag (FK to hashtags.hashtag_id)
    PRIMARY KEY (post_hashtag_id),
    CONSTRAINT unique_post_hashtag UNIQUE (post_id, hashtag_id) -- prevent duplicate tags on a post
)
CREATE TABLE social_media.messages (
    message_id character varying(64) NOT NULL, -- unique identifier for the message
    conversation_id character varying(64) NOT NULL, -- identifier for the conversation thread (FK to conversations.conversation_id)
    sender_user_id character varying(64) NOT NULL, -- identifier of the sender (FK to users.user_id)
    content text, -- textual content of the message
    media_url text, -- URL to attached media (image/video)
    media_type character varying(20), -- type of media ('image', 'video', null)
    sent_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, -- timestamp when message was sent
    read_at timestamp, -- timestamp when message was read by recipient(s)
    PRIMARY KEY (message_id)
)
CREATE TABLE social_media.conversations (
    conversation_id character varying(64) NOT NULL, -- unique identifier for the conversation
    created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, -- timestamp when conversation was initiated
    last_message_at timestamp, -- timestamp of the last message in the conversation
    is_group_chat boolean NOT NULL DEFAULT false, -- indicates if it's a group chat or direct message
    group_name character varying(100), -- name of the group chat (if applicable)
    PRIMARY KEY (conversation_id)
)
CREATE TABLE social_media.conversation_participants (
    participant_id character varying(64) NOT NULL, -- unique identifier for the participant entry
    conversation_id character varying(64) NOT NULL, -- identifier of the conversation (FK to conversations.conversation_id)
    user_id character varying(64) NOT NULL, -- identifier of the user in the conversation (FK to users.user_id)
    joined_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, -- timestamp when user joined the conversation
    last_read_at timestamp, -- timestamp indicating up to when the user has read messages
    PRIMARY KEY (participant_id),
    CONSTRAINT unique_user_conversation UNIQUE (conversation_id, user_id) -- prevent user being added multiple times
)
CREATE TABLE social_media.notifications (
    notification_id character varying(64) NOT NULL, -- unique identifier for the notification
    recipient_user_id character varying(64) NOT NULL, -- user receiving the notification (FK to users.user_id)
    sender_user_id character varying(64), -- user triggering the notification (FK to users.user_id, can be null for system notifications)
    notification_type character varying(30) NOT NULL, -- type of notification ('like', 'comment', 'follow', 'mention', 'message')
    target_entity_id character varying(64), -- ID of the related entity (post_id, comment_id, user_id, conversation_id)
    target_entity_type character varying(20), -- type of the related entity ('post', 'comment', 'user', 'conversation')
    created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, -- timestamp notification was created
    read_at timestamp, -- timestamp notification was marked as read
    PRIMARY KEY (notification_id)
)
##Table Structure
CREATE TABLE gaming_technology.players ( player_id uuid, username text, email text, password_hash text, registration_date timestamp with time zone, last_login timestamp with time zone, country_code text, status text, profile_data jsonb )
CREATE TABLE gaming_technology.in_game_items ( item_id uuid, game_id uuid, item_name text, item_type text, description text, rarity text, cost_currency text, cost_amount numeric, attributes jsonb )
##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 )

[User] List all users who have a non-empty bio and a profile picture URL.

[Assistant]
SELECT
  user_id,
  username,
  full_name,
  bio,
  profile_picture_url
FROM social_media.users
WHERE
  bio IS NOT NULL AND profile_picture_url IS NOT NULL;

[User] Could you list all unique item types available in the system and the number of items that belong to each type?

[Assistant]
SELECT item_type, COUNT(item_id) AS item_count
FROM gaming_technology.in_game_items
GROUP BY item_type;

[User] Please also include the total number of players from the players table for each item type.

[Assistant]
SELECT i.item_type, COUNT(i.item_id) AS item_count, (
    SELECT COUNT(*) FROM gaming_technology.players
) AS total_players
FROM gaming_technology.in_game_items i
GROUP BY i.item_type;

[User] Now, show only item types that have more than 2 items.

[Assistant]
SELECT i.item_type, COUNT(i.item_id) AS item_count, (
    SELECT COUNT(*) FROM gaming_technology.players
) AS total_players
FROM gaming_technology.in_game_items i
GROUP BY i.item_type
HAVING COUNT(i.item_id) > 2;

[User] Show me all replies to comments, including the reply's comment ID, the parent comment ID, and the content.

[Assistant] SELECT comment_id, parent_comment_id, content FROM social_media.comments WHERE parent_comment_id IS NOT NULL;

[User] I also want to see which post each reply was made on. Can you include the post ID as well?

[Assistant] SELECT comment_id, parent_comment_id, post_id, content FROM social_media.comments WHERE parent_comment_id IS NOT NULL;

[User] Now, only show replies made after June 1, 2024.

[Assistant] SELECT comment_id, parent_comment_id, post_id, content FROM social_media.comments WHERE parent_comment_id IS NOT NULL AND created_at > '2024-06-01';


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement. ##Table Structure
CREATE TABLE government_services.citizens (
    citizen_id character varying(64) NOT NULL,  -- unique identifier for the citizen
    national_id_number character varying(128) NOT NULL UNIQUE, -- official national identification number
    first_name character varying(100) NOT NULL,
    last_name character varying(100) NOT NULL,
    date_of_birth date NOT NULL,
    gender character varying(20),
    primary_address text NOT NULL, -- full primary residential address
    contact_email character varying(128) UNIQUE,
    contact_phone character varying(32),
    registration_date timestamp NOT NULL, -- when the citizen profile was created
    is_verified boolean DEFAULT false, -- whether identity has been officially verified
    PRIMARY KEY (citizen_id)
)
CREATE TABLE government_services.agencies ( agency_id character varying(64) NOT NULL, agency_name character varying(255) NOT NULL, jurisdiction_level character varying(50) NOT NULL, primary_contact_email character varying(128), main_phone_number character varying(32), website_url character varying(255), established_date date, parent_agency_id character varying(64), PRIMARY KEY (agency_id) )
CREATE TABLE government_services.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 )
##Table Structure
CREATE TABLE government_services.citizens ( citizen_id text PRIMARY KEY, national_id_number text, first_name text, last_name text, date_of_birth date, gender text, primary_address text, contact_email text, contact_phone text, registration_date timestamp, is_verified boolean )
CREATE TABLE government_services.services ( service_id text, agency_id text, service_name text, description text, category text, eligibility_criteria text, standard_fee numeric, average_processing_time_days integer, is_active boolean, online_application_url text )
CREATE TABLE government_services.documents (
    document_id character varying(64) NOT NULL, -- unique identifier for the document instance
    application_id character varying(64), -- FK to applications table (optional, could be linked to citizen directly)
    citizen_id character varying(64) NOT NULL, -- FK to citizens table
    document_type character varying(100) NOT NULL, -- e.g., Passport Scan, Proof of Address, Birth Certificate
    file_reference text NOT NULL, -- reference to the stored file (e.g., S3 URL, internal path)
    upload_timestamp timestamp NOT NULL,
    expiry_date date,
    verification_status character varying(30) DEFAULT 'Pending', -- e.g., Pending, Verified, Rejected
    verified_by_employee_id character varying(64), -- FK to employees table
    verification_timestamp timestamp,
    PRIMARY KEY (document_id)
)
CREATE TABLE government_services.service_locations ( location_id character varying(64) NOT NULL, agency_id character varying(64) NOT NULL, location_name character varying(200), address text NOT NULL, city character varying(100), state character varying(50), postal_code character varying(20), latitude numeric(9, 6), longitude numeric(9, 6), operating_hours text, contact_phone character varying(32), is_accessible boolean, PRIMARY KEY (location_id) )
CREATE TABLE government_services.notifications ( notification_id text PRIMARY KEY, citizen_id text, application_id text, message_subject text, message_body text, channel text, sent_at timestamp, status text, related_entity_type text, related_entity_id text )
##Table Structure
CREATE TABLE transportation.trips ( trip_id character varying(64) NOT NULL, route_id character varying(64), vehicle_id character varying(64) NOT NULL, driver_id character varying(64) NOT NULL, scheduled_departure timestamp with time zone NOT NULL, actual_departure timestamp with time zone, scheduled_arrival timestamp with time zone NOT NULL, actual_arrival timestamp with time zone, origin_location_id character varying(64) NOT NULL, destination_location_id character varying(64) NOT NULL, status character varying(32) NOT NULL, passenger_count integer, cargo_manifest_id character varying(64), PRIMARY KEY (trip_id) )
##Table Structure
CREATE TABLE web3.events ( event_id text PRIMARY KEY, contract_id text, event_name text, data text, emitted_at timestamp, transaction_id text, log_index int )
CREATE TABLE web3.token_transfers ( transfer_id text PRIMARY KEY, token_id text, from_address text, to_address text, value numeric, transaction_id text, log_index int )
##Table Structure
CREATE TABLE transportation.locations ( location_id text PRIMARY KEY, name text, type text, address_line1 text, city text, state_province text, postal_code text, country text, latitude numeric, longitude numeric, timezone text )
CREATE TABLE transportation.maintenance_logs ( log_id text PRIMARY KEY, vehicle_id text, service_date date, odometer_reading int, service_type text, description text, cost numeric, mechanic_name text, next_service_due_date date )
CREATE TABLE transportation.passengers ( passenger_id text PRIMARY KEY, first_name text, last_name text, email text, phone_number text, date_of_birth date, loyalty_program_id text, created_at timestamp )

[User] Retrieve the document_id, document_type, citizen full name, and verification_status for all documents that have no expiry date set.

[Assistant]
SELECT d.document_id,
       d.document_type,
       c.first_name || ' ' || c.last_name AS full_name,
       d.verification_status
FROM government_services.documents d
JOIN government_services.citizens c ON d.citizen_id = c.citizen_id
WHERE d.expiry_date IS NULL;

[User] Show the names of all services and the names of their corresponding agencies that are offered at accessible locations in 'Chicago'.

[Assistant]
SELECT s.service_name, sl.agency_id
FROM government_services.service_locations sl
JOIN government_services.services s ON sl.agency_id = s.agency_id
WHERE sl.city = 'Chicago' AND sl.is_accessible = TRUE;

[User] Show me pairs of trip IDs that used the same vehicle.

[Assistant]
SELECT
  t1.trip_id AS trip1_id,
  t2.trip_id AS trip2_id
FROM transportation.trips AS t1
JOIN transportation.trips AS t2
  ON t1.vehicle_id = t2.vehicle_id
  AND t1.trip_id < t2.trip_id;

[User] Now, filter this list to only include pairs where both trips have a 'Completed' status.

[Assistant]
SELECT
  t1.trip_id AS trip1_id,
  t2.trip_id AS trip2_id
FROM transportation.trips AS t1
JOIN transportation.trips AS t2
  ON t1.vehicle_id = t2.vehicle_id
  AND t1.trip_id < t2.trip_id
WHERE
  t1.status = 'Completed' AND t2.status = 'Completed';

[User] List all token transfers with values greater than 1000, including the token ID and transaction ID.

[Assistant] SELECT transfer_id, token_id, transaction_id, value FROM web3.token_transfers WHERE value > 1000;

[User] Actually, I also need to see the event names associated with these transactions.

[Assistant] SELECT tt.transfer_id, tt.token_id, tt.transaction_id, tt.value, e.event_name FROM web3.token_transfers tt LEFT JOIN web3.events e ON tt.transaction_id = e.transaction_id WHERE tt.value > 1000;

[User] There's a typo in your SQL, it should be 'token_transfers' not 'token_transfers'. Also, sort the results by value in descending order.

[Assistant] SELECT tt.transfer_id, tt.token_id, tt.transaction_id, tt.value, e.event_name FROM web3.token_transfers tt LEFT JOIN web3.events e ON tt.transaction_id = e.transaction_id WHERE tt.value > 1000 ORDER BY tt.value DESC;

[User] Now filter to only show transfers that have at least one associated event.

[Assistant] SELECT tt.transfer_id, tt.token_id, tt.transaction_id, tt.value, e.event_name FROM web3.token_transfers tt JOIN web3.events e ON tt.transaction_id = e.transaction_id WHERE tt.value > 1000 ORDER BY tt.value DESC;

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

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

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

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


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement. ##Table Structure
CREATE TABLE project_fundraising_record ( id.text, project_id.text, project_name.text, rounds_name.text, investment_value.numeric, investment_date.text, introduction.text, valuation.numeric )
##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.room_types ( room_type_id text PRIMARY KEY, property_id text, type_name text, description text, base_rate numeric, max_occupancy int, bed_type text, area_sqft numeric, amenities text )
CREATE TABLE hospitality_technology.guests ( guest_id text PRIMARY KEY, first_name text, last_name text, email text, phone_number text, date_of_birth date, address_line1 text, city text, state_province text, postal_code text, country_code text, preferences text, loyalty_member_id text, communication_consent boolean, created_at timestamp, updated_at timestamp )
CREATE TABLE hospitality_technology.staff ( staff_id text 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.payments ( payment_id text PRIMARY KEY, 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 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 )
##Table Structure
CREATE TABLE government_services.service_locations ( location_id character varying(64) NOT NULL, agency_id character varying(64) NOT NULL, location_name character varying(200), address text NOT NULL, city character varying(100), state character varying(50), postal_code character varying(20), latitude numeric(9, 6), longitude numeric(9, 6), operating_hours text, contact_phone character varying(32), is_accessible boolean, PRIMARY KEY (location_id) )
CREATE TABLE government_services.appointments ( appointment_id character varying(64) NOT NULL, citizen_id character varying(64) NOT NULL, employee_id character varying(64), location_id character varying(64), service_id character varying(64), scheduled_start_time timestamp NOT NULL, scheduled_end_time timestamp, purpose text NOT NULL, status character varying(30) NOT NULL, booking_method character varying(50), created_at timestamp NOT NULL, notes text, PRIMARY KEY (appointment_id) )
##Table Structure
CREATE TABLE financial_services.accounts ( account_id character varying(64) NOT NULL, customer_id character varying(64) NOT NULL, account_number character varying(128) NOT NULL UNIQUE, account_type character varying(50) NOT NULL, balance numeric(19, 4) NOT NULL DEFAULT 0.00, currency character varying(3) NOT NULL, opened_date date NOT NULL, status character varying(32) NOT NULL, interest_rate numeric(5, 4), last_updated_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, PRIMARY KEY (account_id), FOREIGN KEY (customer_id) REFERENCES financial_services.customers(customer_id) )
##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 )

[User] Which project had the largest single fundraising in each investment round, along with the round's name and introduction?

[Assistant] SELECT t1.project_name, t1.rounds_name, t1.investment_value, t1.introduction FROM project_fundraising_record t1 INNER JOIN (SELECT rounds_name, MAX(investment_value) AS max_value FROM project_fundraising_record GROUP BY rounds_name) t2 ON t1.rounds_name = t2.rounds_name AND t1.investment_value = t2.max_value;

[User] Instead of just one, can you show the top two fundraisings in each round?

[Assistant] SELECT project_name, rounds_name, investment_value, introduction FROM (SELECT *, ROW_NUMBER() OVER (PARTITION BY rounds_name ORDER BY investment_value DESC) AS rn FROM project_fundraising_record) tmp WHERE rn <= 2;

[User] Can you add the valuation for each project in the output as well?

[Assistant] SELECT project_name, rounds_name, investment_value, valuation, introduction FROM (SELECT *, ROW_NUMBER() OVER (PARTITION BY rounds_name ORDER BY investment_value DESC) AS rn FROM project_fundraising_record) tmp WHERE rn <= 2;

[User] Show me only those top two projects per round where the valuation is greater than 100 million.

[Assistant] SELECT project_name, rounds_name, investment_value, valuation, introduction FROM (SELECT *, ROW_NUMBER() OVER (PARTITION BY rounds_name ORDER BY investment_value DESC) AS rn FROM project_fundraising_record) tmp WHERE rn <= 2 AND valuation > 100000000;

[User] Which staff members are managing properties, and what are the names and email addresses of those properties?

[Assistant] SELECT s.staff_id, s.first_name, s.last_name, p.property_name, p.email_address FROM hospitality_technology.staff s INNER JOIN hospitality_technology.properties p ON s.staff_id = p.manager_staff_id;

[User] Only include properties located in the United States and list the staff position as well.

[Assistant] SELECT s.staff_id, s.first_name, s.last_name, s.position, p.property_name, p.email_address FROM hospitality_technology.staff s INNER JOIN hospitality_technology.properties p ON s.staff_id = p.manager_staff_id WHERE p.country_code = 'US';

[User] How many prescriptions have been issued per patient?

[Assistant]
SELECT patient_id, COUNT(*) AS prescription_count
FROM healthcare.prescriptions
GROUP BY patient_id;

[User] Only show patients who have more than 5 prescriptions.

[Assistant]
SELECT patient_id, COUNT(*) AS prescription_count
FROM healthcare.prescriptions
GROUP BY patient_id
HAVING COUNT(*) > 5;

[User] List the number of appointments for each booking method.

[Assistant]
SELECT
  a.booking_method,
  COUNT(*) AS appointment_count
FROM appointments a
GROUP BY a.booking_method;

[User] Filter this to only include booking methods that have more than 50 appointments.

[Assistant]
SELECT
  a.booking_method,
  COUNT(*) AS appointment_count
FROM appointments a
GROUP BY a.booking_method
HAVING COUNT(*) > 50;

[User] Also only consider appointments that are scheduled in the state of 'Texas'.

[Assistant]
SELECT
  a.booking_method,
  COUNT(*) AS appointment_count
FROM appointments a
JOIN service_locations sl
  ON a.location_id = sl.location_id
WHERE sl.state = 'Texas'
GROUP BY a.booking_method
HAVING COUNT(*) > 50;

[User] Now show the results ordered by appointment_count descending and limit to top 3 methods.

[Assistant]
SELECT
  a.booking_method,
  COUNT(*) AS appointment_count
FROM appointments a
JOIN service_locations sl
  ON a.location_id = sl.location_id
WHERE sl.state = 'Texas'
GROUP BY a.booking_method
HAVING COUNT(*) > 50
ORDER BY appointment_count DESC
LIMIT 3;

[User] What is the total balance for each currency in the accounts table?

[Assistant] SELECT currency, SUM(balance) AS total_balance FROM financial_services.accounts GROUP BY currency;

[User] Can you also show the number of accounts for each currency?

[Assistant] SELECT currency, COUNT(account_id) AS number_of_accounts, SUM(balance) AS total_balance FROM financial_services.accounts GROUP BY currency;

[User] Only include accounts with status 'ACTIVE' in the calculation.

[Assistant] SELECT currency, COUNT(account_id) AS number_of_accounts, SUM(balance) AS total_balance FROM financial_services.accounts WHERE status = 'ACTIVE' GROUP BY currency;

[User] Show me the name and type for all the locations.

[Assistant] SELECT name, type FROM transportation.locations

[User] Now, filter this list to only include locations whose type is either 'Distribution Center' or 'Warehouse'.

[Assistant] SELECT name, type FROM transportation.locations WHERE type IN ('Distribution Center', 'Warehouse')


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement. ##Table Structure
CREATE TABLE 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 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 )
CREATE TABLE hospitality_technology.room_types ( room_type_id text PRIMARY KEY, property_id text, type_name text, description text, base_rate numeric, max_occupancy int, bed_type text, area_sqft numeric, amenities text )
CREATE TABLE hospitality_technology.guests ( guest_id text PRIMARY KEY, first_name text, last_name text, email text, phone_number text, date_of_birth date, address_line1 text, city text, state_province text, postal_code text, country_code text, preferences text, loyalty_member_id text, communication_consent boolean, created_at timestamp, updated_at timestamp )
CREATE TABLE hospitality_technology.reservations ( reservation_id text PRIMARY KEY, property_id text, guest_id text, room_id text, room_type_id text, check_in_date date, check_out_date date, actual_check_in_ts timestamp, actual_check_out_ts timestamp, num_adults int, num_children int, status text, booking_source text, rate_plan_id text, total_amount numeric, amount_paid numeric, special_requests text, created_at timestamp, updated_at timestamp )
CREATE TABLE hospitality_technology.staff ( staff_id text 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.payments ( payment_id text PRIMARY KEY, reservation_id text, guest_id text, bill_id text, amount numeric, currency_code text, payment_method text, card_type text, card_last_four text, transaction_ref text, payment_timestamp timestamp, status text, staff_id_processed text, notes text )
CREATE TABLE hospitality_technology.reviews ( review_id text PRIMARY KEY, property_id text, reservation_id text, guest_id text, rating_overall int, rating_cleanliness int, rating_service int, rating_location int, rating_value int, 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 social_media.comments ( comment_id text, 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, user_id text, post_id text, comment_id text, created_at timestamp )
CREATE TABLE social_media.follows ( follow_id text, follower_user_id text, following_user_id text, created_at timestamp )
CREATE TABLE social_media.messages ( message_id text, conversation_id text, sender_user_id text, content text, media_url text, media_type text, sent_at timestamp, read_at timestamp )
CREATE TABLE social_media.conversations ( conversation_id text, created_at timestamp, last_message_at timestamp, is_group_chat boolean, group_name text )
CREATE TABLE social_media.conversation_participants ( participant_id text, conversation_id text, user_id text, joined_at timestamp, last_read_at timestamp )
##Table Structure
CREATE TABLE social_media.follows ( follow_id.text, follower_user_id.text, following_user_id.text, created_at.timestamp )

[User] List pairs of documents uploaded by the same lawyer, showing uploader ID and both document names.

[Assistant] SELECT d1.uploaded_by_lawyer_id, d1.document_name AS doc1, d2.document_name AS doc2 FROM legal_services.documents d1 JOIN legal_services.documents d2 ON d1.uploaded_by_lawyer_id = d2.uploaded_by_lawyer_id AND d1.document_id < d2.document_id;

[User] Only include pairs where the upload timestamps are within 7 days of each other.

[Assistant] SELECT d1.uploaded_by_lawyer_id, d1.document_name AS doc1, d2.document_name AS doc2 FROM legal_services.documents d1 JOIN legal_services.documents d2 ON d1.uploaded_by_lawyer_id = d2.uploaded_by_lawyer_id AND d1.document_id < d2.document_id AND ABS(EXTRACT(EPOCH FROM (d1.upload_timestamp - d2.upload_timestamp)))/86400 <= 7;

[User] List all staff members who are not managers, including their first name, last name, position, and the name of the property they work at.

[Assistant] SELECT T1.first_name, T1.last_name, T1.position, T2.property_name FROM hospitality_technology.staff AS T1 INNER JOIN hospitality_technology.properties AS T2 ON T1.property_id = T2.property_id WHERE T1.staff_id NOT IN (SELECT DISTINCT manager_id FROM hospitality_technology.staff WHERE manager_id IS NOT NULL);

[User] I need to find users who follow both 'U100' and 'U200'. Show the follower_user_id and the creation dates of both follow events.

[Assistant]
SELECT f1.follower_user_id,
       f1.created_at AS follow_u100_at,
       f2.created_at AS follow_u200_at
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 = 'U200';

[User] Actually, only include cases where both follow events occurred in the same calendar month.

[Assistant]
SELECT f1.follower_user_id,
       f1.created_at AS follow_u100_at,
       f2.created_at AS follow_u200_at
FROM social_media.follows f1
JOIN social_media.follows f2
  ON f1.follower_user_id = f2.follower_user_id
     AND DATE_TRUNC('month', f1.created_at) = DATE_TRUNC('month', f2.created_at)
WHERE f1.following_user_id = 'U100'
  AND f2.following_user_id = 'U200';

[User] Find users who followed at least two different people on the same calendar day. For each such user, list their ID, the IDs of the two people they followed, and the creation times of those two follow events.

[Assistant] SELECT f1.follower_user_id, f1.following_user_id AS followed_user_1_id, f2.following_user_id AS followed_user_2_id, f1.created_at AS follow_1_created_at, f2.created_at AS follow_2_created_at FROM social_media.follows AS f1 JOIN social_media.follows AS f2 ON f1.follower_user_id = f2.follower_user_id WHERE f1.following_user_id != f2.following_user_id AND DATE(f1.created_at) = DATE(f2.created_at);

[User] Also, only include pairs of follows where the two follow events happened within 30 minutes of each other on that same day.

[Assistant] SELECT f1.follower_user_id, f1.following_user_id AS followed_user_1_id, f2.following_user_id AS followed_user_2_id, f1.created_at AS follow_1_created_at, f2.created_at AS follow_2_created_at FROM social_media.follows AS f1 JOIN social_media.follows AS f2 ON f1.follower_user_id = f2.follower_user_id WHERE f1.following_user_id != f2.following_user_id AND DATE(f1.created_at) = DATE(f2.created_at) AND ABS(EXTRACT(EPOCH FROM (f1.created_at - f2.created_at))) <= 1800;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement. ##Table Structure
CREATE TABLE gaming_technology.player_achievements ( player_achievement_id.uuid, player_id.uuid, achievement_id.uuid, unlocked_at.timestamptz )
##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)
)
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)
)
##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.employees ( employee_id character varying(64) NOT NULL, agency_id character varying(64) NOT NULL, first_name character varying(100) NOT NULL, last_name character varying(100) NOT NULL, job_title character varying(150) NOT NULL, department character varying(100), work_email character varying(128) NOT NULL UNIQUE, work_phone character varying(32), hire_date date NOT NULL, termination_date date, access_level character varying(50), manager_employee_id character varying(64), PRIMARY KEY (employee_id) )
CREATE TABLE government_services.service_locations ( location_id character varying(64) NOT NULL, agency_id character varying(64) NOT NULL, location_name character varying(200), address text NOT NULL, city character varying(100), state character varying(50), postal_code character varying(20), latitude numeric(9, 6), longitude numeric(9, 6), operating_hours text, contact_phone character varying(32), is_accessible boolean, PRIMARY KEY (location_id) )
CREATE TABLE government_services.appointments ( appointment_id character varying(64) NOT NULL, citizen_id character varying(64) NOT NULL, employee_id character varying(64), location_id character varying(64), service_id character varying(64), scheduled_start_time timestamp NOT NULL, scheduled_end_time timestamp, purpose text NOT NULL, status character varying(30) NOT NULL, booking_method character varying(50), created_at timestamp NOT NULL, notes text, PRIMARY KEY (appointment_id) )
CREATE TABLE government_services.notifications ( notification_id character varying(64) NOT NULL, citizen_id character varying(64) NOT NULL, application_id character varying(64), message_subject character varying(255), message_body text NOT NULL, channel character varying(30) NOT NULL, sent_at timestamp NOT NULL, status character varying(30) NOT NULL, related_entity_type character varying(50), related_entity_id character varying(64), PRIMARY KEY (notification_id) )
##Table Structure
CREATE TABLE hospitality_technology.service_orders ( order_id text PRIMARY KEY, reservation_id text, guest_id text, service_id text, staff_id_ordered text, staff_id_delivered text, order_timestamp timestamp, delivery_timestamp timestamp, quantity int, unit_price numeric, total_price numeric, status text, notes text, bill_id text )

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

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

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

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

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

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

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

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

[User] Show the average passenger_count for each trip status.

[Assistant]
SELECT status, AVG(passenger_count) AS avg_passengers
FROM transportation.trips
GROUP BY status;

[User] Only include statuses with at least 10 trips.

[Assistant]
SELECT status, AVG(passenger_count) AS avg_passengers
FROM transportation.trips
GROUP BY status
HAVING COUNT(*) >= 10;

[User] Retrieve each citizen's first_name, last_name, and their most recent notification's message_subject and sent_at, only for notifications sent via 'Email'.

[Assistant]
SELECT c.first_name,
       c.last_name,
       n.message_subject,
       n.sent_at
FROM government_services.citizens c
JOIN (
  SELECT DISTINCT ON (citizen_id)
         citizen_id,
         message_subject,
         sent_at
  FROM government_services.notifications
  WHERE channel = 'Email'
  ORDER BY citizen_id, sent_at DESC
) n ON c.citizen_id = n.citizen_id;

[User] Show me the total quantity and total revenue for each service, along with the number of unique guests who ordered each service.

[Assistant] SELECT service_id, SUM(quantity) AS total_quantity, SUM(total_price) AS total_revenue, COUNT(DISTINCT guest_id) AS unique_guest_count FROM hospitality_technology.service_orders GROUP BY service_id;

[User] Now, only include services where the total revenue is above 1000 and sort by total_revenue descending.

[Assistant] SELECT service_id, SUM(quantity) AS total_quantity, SUM(total_price) AS total_revenue, COUNT(DISTINCT guest_id) AS unique_guest_count FROM hospitality_technology.service_orders GROUP BY service_id HAVING SUM(total_price) > 1000 ORDER BY total_revenue DESC;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement. ##Table Structure
CREATE TABLE social_media.likes ( like_id text PRIMARY KEY, user_id text, post_id text, comment_id text, created_at timestamp )
##Table Structure
CREATE TABLE trading_platform.trades (
    trade_id character varying(64) NOT NULL,  -- unique identifier for the trade
    order_id character varying(64) NOT NULL, -- identifier of the order that led to the trade
    buyer_id character varying(64) NOT NULL, -- identifier of the buyer
    seller_id character varying(64) NOT NULL, -- identifier of the seller
    asset_id character varying(64) NOT NULL, -- identifier of the asset being traded
    quantity numeric(38,14) NOT NULL, -- quantity of the asset in the trade
    price numeric(38,14) NOT NULL, -- price per unit of the asset
    traded_at timestamp NOT NULL, -- time when the trade was executed
    PRIMARY KEY (trade_id)
)
##Table Structure
CREATE TABLE insurance.policies ( policy_id text, customer_id text, product_id text, agent_id text, policy_number text, start_date date, end_date date, premium_amount numeric, coverage_limit numeric, deductible numeric, status text, issued_at timestamp, cancellation_date date, cancellation_reason text )
CREATE TABLE insurance.claims ( claim_id text, policy_id text, customer_id text, incident_date timestamp, reported_date timestamp, description text, estimated_loss numeric, status text, settlement_amount numeric, settlement_date date, claim_handler_id text, police_report_number text )
CREATE TABLE insurance.premium_payments ( payment_id text, policy_id text, customer_id text, payment_date timestamp, amount_paid numeric, payment_method text, transaction_reference text, due_date date, payment_period_start date, payment_period_end date, status text )
CREATE TABLE insurance.claim_documents ( document_id text, claim_id text, document_type text, file_name text, file_path text, file_size_bytes integer, mime_type text, uploaded_by text, uploaded_at timestamp, description text )
CREATE TABLE insurance.policy_beneficiaries ( beneficiary_id text, policy_id text, customer_id text, first_name text, last_name text, relationship text, percentage_share numeric, contact_info text, added_at timestamp )
##Table Structure
CREATE TABLE social_media.conversations ( conversation_id.text, created_at.timestamp, last_message_at.timestamp, is_group_chat.boolean, group_name.text )
CREATE TABLE social_media.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 social_media.users ( user_id text, username text, email text, password_hash text, full_name text, profile_picture_url text, bio text, location text, created_at timestamp, updated_at timestamp, is_verified boolean )
CREATE TABLE social_media.posts ( post_id text, user_id text, content text, media_url text, media_type text, created_at timestamp, updated_at timestamp, visibility text, location_lat numeric, location_lon numeric )
CREATE TABLE social_media.comments ( comment_id text, post_id text, user_id text, parent_comment_id text, content text, created_at timestamp, updated_at timestamp )
CREATE TABLE social_media.hashtags ( hashtag_id text, tag_name text, created_at timestamp )
CREATE TABLE social_media.post_hashtags ( post_hashtag_id text, post_id text, hashtag_id text )
CREATE TABLE social_media.messages ( message_id text, conversation_id text, sender_user_id text, content text, media_url text, media_type text, sent_at timestamp, read_at timestamp )
CREATE TABLE social_media.conversations ( conversation_id text, created_at timestamp, last_message_at timestamp, is_group_chat boolean, group_name text )
CREATE TABLE social_media.conversation_participants ( participant_id text, conversation_id text, user_id text, joined_at timestamp, last_read_at timestamp )
CREATE TABLE social_media.notifications ( notification_id text, recipient_user_id text, sender_user_id text, notification_type text, target_entity_id text, target_entity_type text, created_at timestamp, read_at timestamp )
CREATE TABLE social_media.user_settings ( setting_id text, user_id text, theme text, email_notifications_enabled boolean, push_notifications_enabled boolean, private_profile boolean, updated_at timestamp )

[User] Find the total number of likes made on posts versus comments. Show two columns: like_type (either 'post' or 'comment') and like_count.

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

[User] Actually, I want to see this broken down per user as well. Include user_id in the results.

[Assistant]
SELECT user_id, CASE WHEN post_id IS NOT NULL THEN 'post' ELSE 'comment' END AS like_type, COUNT(*) AS like_count
FROM social_media.likes
WHERE post_id IS NOT NULL OR comment_id IS NOT NULL
GROUP BY user_id, like_type;

[User] Only include users who have liked at least 2 comments.

[Assistant]
SELECT user_id, 'comment' AS like_type, COUNT(*) AS like_count
FROM social_media.likes
WHERE comment_id IS NOT NULL
GROUP BY user_id
HAVING COUNT(*) >= 2;

[User] I want a summary for each user showing their total buy value and total sell value across all trades.

[Assistant]
SELECT
  COALESCE(b.user_id, s.user_id) AS user_id,
  COALESCE(b.total_buy, 0) AS total_buy_value,
  COALESCE(s.total_sell, 0) AS total_sell_value
FROM
  (
    SELECT buyer_id AS user_id, SUM(quantity * price) AS total_buy
    FROM trading_platform.trades
    GROUP BY buyer_id
  ) b
FULL OUTER JOIN
  (
    SELECT seller_id AS user_id, SUM(quantity * price) AS total_sell
    FROM trading_platform.trades
    GROUP BY seller_id
  ) s
ON b.user_id = s.user_id;

[User] Actually, I only care about users who have both bought and sold assets.

[Assistant]
SELECT
  b.user_id,
  b.total_buy AS total_buy_value,
  s.total_sell AS total_sell_value
FROM
  (
    SELECT buyer_id AS user_id, SUM(quantity * price) AS total_buy
    FROM trading_platform.trades
    GROUP BY buyer_id
  ) b
INNER JOIN
  (
    SELECT seller_id AS user_id, SUM(quantity * price) AS total_sell
    FROM trading_platform.trades
    GROUP BY seller_id
  ) s
ON b.user_id = s.user_id;

[User] Show all document types uploaded for claim ID 'CLM12345' and the time each was uploaded.

[Assistant]
SELECT document_type, uploaded_at
FROM insurance.claim_documents
WHERE claim_id = 'CLM12345';

[User] Get the count of unread 'message' notifications per group chat, showing conversation_id, group_name, and unread_message_notifications.

[Assistant]
SELECT c.conversation_id,
       c.group_name,
       COUNT(n.notification_id) AS unread_message_notifications
FROM social_media.conversations c
JOIN social_media.notifications n
  ON n.target_entity_type = 'conversation'
  AND n.target_entity_id = c.conversation_id
  AND c.is_group_chat = true
  AND n.notification_type = 'message'
  AND n.read_at IS NULL
GROUP BY c.conversation_id, c.group_name;

[User] Actually, only include group chats where unread_message_notifications > 5.

[Assistant]
SELECT c.conversation_id,
       c.group_name,
       COUNT(n.notification_id) AS unread_message_notifications
FROM social_media.conversations c
JOIN social_media.notifications n
  ON n.target_entity_type = 'conversation'
  AND n.target_entity_id = c.conversation_id
  AND c.is_group_chat = true
  AND n.notification_type = 'message'
  AND n.read_at IS NULL
GROUP BY c.conversation_id, c.group_name
HAVING COUNT(n.notification_id) > 5;

[User] For each private conversation (is_group_chat = false), list the conversation_id and the usernames of its two participants.

[Assistant]
SELECT c.conversation_id,
       u1.username AS participant_one,
       u2.username AS participant_two
FROM social_media.conversations c
JOIN social_media.conversation_participants cp1 ON c.conversation_id = cp1.conversation_id
JOIN social_media.conversation_participants cp2 ON c.conversation_id = cp2.conversation_id AND cp2.user_id <> cp1.user_id
JOIN social_media.users u1 ON cp1.user_id = u1.user_id
JOIN social_media.users u2 ON cp2.user_id = u2.user_id
WHERE c.is_group_chat = false
  AND cp1.user_id < cp2.user_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
// Node Label: :Station
// Properties:
//   station_id: String (Constraint: UNIQUE)
//   station_name: String
//   city: String (Index recommended)
//   state_province: String
//   country_code: String
//   address: String
//   timezone: String
//   number_of_platforms: Integer
//   created_at: DateTime
//   last_updated_at: DateTime
// Example Cypher CREATE:
// CREATE (:Station {station_id: 'station_xyz', station_name: 'Grand Central Terminal', city: 'New York', ...})
// Node Label: :Platform
// Properties:
//   platform_id: String (Constraint: UNIQUE)
//   platform_number: String
//   track_number: String
//   status: String
//   length_meters: Float
//   accessible: Boolean
// Relationship: (:Platform)-[:LOCATED_AT]->(:Station)
// Example Cypher CREATE:
// MATCH (s:Station {station_id: 'station_xyz'})
// CREATE (p:Platform {platform_id: 'plat_123', ...})-[:LOCATED_AT]->(s)
// Node Label: :Train
// Properties:
//   train_id: String (Constraint: UNIQUE)
//   train_number: String (Constraint: UNIQUE)
//   model: String
//   manufacturer: String
//   year_manufactured: Integer
//   capacity: Integer
//   status: String
//   last_maintenance_date: Date
//   next_maintenance_date: Date
// Example Cypher CREATE:
// CREATE (:Train {train_id: 'train_789', train_number: 'Acela 2151', ...})
// Node Label: :TrainCar
// Properties:
//   car_id: String (Constraint: UNIQUE)
//   car_number: String
//   car_type: String
//   class: String
//   capacity: Integer
//   features: String (Or List<String> if driver supports)
// Relationship: (:TrainCar)-[:PART_OF_TRAIN]->(:Train)
// Example Cypher CREATE:
// MATCH (t:Train {train_id: 'train_789'})
// CREATE (c:TrainCar {car_id: 'car_abc', ...})-[:PART_OF_TRAIN]->(t)
// Node Label: :Route
// Properties:
//   route_id: String (Constraint: UNIQUE)
//   route_name: String
//   description: String
//   is_active: Boolean
// Relationships:
//   (:Route)-[:STARTS_AT]->(:Station)
//   (:Route)-[:ENDS_AT]->(:Station)
// Example Cypher CREATE:
// MATCH (origin:Station {station_id: 'station_bos'}), (dest:Station {station_id: 'station_was'})
// CREATE (r:Route {route_id: 'route_ne_corr', ...})-[:STARTS_AT]->(origin), (r)-[:ENDS_AT]->(dest)
// Relationship: (:Route)-[rel:HAS_STOP]->(:Station)
// Relationship Properties on :HAS_STOP:
//   sequence_order: Integer
//   distance_from_previous_km: Float
//   typical_stop_duration_minutes: Integer
// Example Cypher CREATE:
// MATCH (r:Route {route_id: 'route_ne_corr'}), (s:Station {station_id: 'station_pvd'})
// CREATE (r)-[:HAS_STOP {sequence_order: 2, distance_from_previous_km: 70.5, ...}]->(s)
// Node Label: :ScheduledTrip (or just :Trip)
// Properties:
//   schedule_id: String (Constraint: UNIQUE)
//   departure_datetime: DateTime
//   arrival_datetime: DateTime
//   status: String
//   notes: String
// Relationships:
//   (:ScheduledTrip)-[:USES_TRAIN]->(:Train)
//   (:ScheduledTrip)-[:FOLLOWS_ROUTE]->(:Route)
// Example Cypher CREATE:
// MATCH (t:Train {train_id: 'train_789'}), (r:Route {route_id: 'route_ne_corr'})
// CREATE (sched:ScheduledTrip {schedule_id: 'sched_1122', ...})-[:USES_TRAIN]->(t), (sched)-[:FOLLOWS_ROUTE]->(r)
// Relationship: (:ScheduledTrip)-[rel:SCHEDULED_STOP]->(:Station)
// Relationship Properties on :SCHEDULED_STOP:
//   sequence_order: Integer
//   platform_id: String (references Platform node if modeled, or just store ID)
//   scheduled_arrival_time: DateTime
//   scheduled_departure_time: DateTime
//   actual_arrival_time: DateTime
//   actual_departure_time: DateTime
//   status: String
// Example Cypher CREATE:
// MATCH (sched:ScheduledTrip {schedule_id: 'sched_1122'}), (s:Station {station_id: 'station_pvd'})
// CREATE (sched)-[:SCHEDULED_STOP {sequence_order: 2, platform_id: 'plat_pvd_1', ...}]->(s)
// Node Label: :Passenger
// Properties:
//   passenger_id: String (Constraint: UNIQUE)
//   first_name: String
//   last_name: String
//   email: String (Constraint: UNIQUE, if not null)
//   phone_number: String (Constraint: UNIQUE, if not null)
//   date_of_birth: Date
//   loyalty_program_id: String
//   created_at: DateTime
// Example Cypher CREATE:
// CREATE (:Passenger {passenger_id: 'pass_pqr', first_name: 'Alice', ...})
// Node Label: :Booking
// Properties:
//   booking_id: String (Constraint: UNIQUE)
//   booking_datetime: DateTime
//   status: String
//   total_price: Float
//   currency_code: String
//   special_requests: String
// Relationships:
//   (:Passenger)-[:MADE_BOOKING]->(:Booking)
//   (:Booking)-[:FOR_TRIP]->(:ScheduledTrip)
// Example Cypher CREATE:
// MATCH (p:Passenger {passenger_id: 'pass_pqr'}), (sched:ScheduledTrip {schedule_id: 'sched_1122'})
// CREATE (p)-[:MADE_BOOKING]->(b:Booking {booking_id: 'book_zyx', ...})-[:FOR_TRIP]->(sched)
// Node Label: :Ticket
// Properties:
//   ticket_id: String (Constraint: UNIQUE)
//   seat_number: String
//   ticket_type: String
//   price: Float
//   is_checked_in: Boolean
//   qr_code_data: String
// Relationships:
//   (:Ticket)-[:PART_OF_BOOKING]->(:Booking)
//   (:Ticket)-[:ASSIGNED_TO_CAR]->(:TrainCar)
// Example Cypher CREATE:
// MATCH (b:Booking {booking_id: 'book_zyx'}), (c:TrainCar {car_id: 'car_abc'})
// CREATE (t:Ticket {ticket_id: 'tkt_1a2b', ...})-[:PART_OF_BOOKING]->(b), (t)-[:ASSIGNED_TO_CAR]->(c)
// Node Label: :Staff
// Properties:
//   staff_id: String (Constraint: UNIQUE)
//   first_name: String
//   last_name: String
//   role: String
//   employee_number: String (Constraint: UNIQUE)
//   hire_date: Date
//   contact_email: String (Constraint: UNIQUE, if not null)
//   contact_phone: String
//   is_active: Boolean
// Relationship (Optional):
//   (:Staff)-[:BASED_AT]->(:Station)
// Example Cypher CREATE:
// CREATE (:Staff {staff_id: 'staff_mno', first_name: 'Bob', ...})
// OPTIONAL MATCH (s:Station {station_id: 'station_xyz'}) // If primary_station_id exists
// WITH s, staff_mno // Need to get the created staff node reference
// WHERE s IS NOT NULL
// CREATE (staff_mno)-[:BASED_AT]->(s)
##Table Structure
CREATE TABLE insurance.claims ( claim_id character varying(64) NOT NULL, policy_id character varying(64) NOT NULL, customer_id character varying(64) NOT NULL, incident_date timestamp NOT NULL, reported_date timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, description text NOT NULL, estimated_loss numeric(15, 2), status character varying(30) NOT NULL, settlement_amount numeric(15, 2), settlement_date date, claim_handler_id character varying(64), police_report_number character varying(100), PRIMARY KEY (claim_id) )

[User] 能否帮我统计特定车站(station_id 为 'station_xyz')的所有工作人员数量？

[Assistant]
MATCH (s:Station {station_id: 'station_xyz'})<-[:BASED_AT]-(staff:Staff)
RETURN COUNT(staff) AS total_staff

[User] Show me the total estimated loss per claim status, and for each status, include the most recent claim's incident date.

[Assistant]
SELECT status, SUM(estimated_loss) AS total_estimated_loss, MAX(incident_date) AS most_recent_incident_date
FROM insurance.claims
GROUP BY status;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement. ##Table Structure
CREATE TABLE gaming_technology.servers ( server_id.uuid, game_id.uuid, server_name.text, region.text, ip_address.text, port.integer, current_players.integer, max_players.integer, status.text, last_heartbeat.timestamptz )
##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 character varying(64) NOT NULL, agency_name character varying(255) NOT NULL, jurisdiction_level character varying(50) NOT NULL, primary_contact_email character varying(128), main_phone_number character varying(32), website_url character varying(255), established_date date, parent_agency_id character varying(64), PRIMARY KEY (agency_id) )
CREATE TABLE government_services.services ( service_id character varying(64) NOT NULL, agency_id character varying(64) NOT NULL, service_name character varying(255) NOT NULL, description text, category character varying(100), eligibility_criteria text, standard_fee numeric(10, 2) DEFAULT 0.00, average_processing_time_days integer, is_active boolean DEFAULT true, online_application_url character varying(255), PRIMARY KEY (service_id) )
CREATE TABLE government_services.applications ( application_id character varying(64) NOT NULL, citizen_id character varying(64) NOT NULL, service_id character varying(64) NOT NULL, submitted_at timestamp NOT NULL, status character varying(50) NOT NULL, last_updated_at timestamp NOT NULL, assigned_employee_id character varying(64), decision_date date, notes text, reference_number character varying(100) UNIQUE, PRIMARY KEY (application_id) )
CREATE TABLE government_services.documents ( document_id 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.payments ( payment_id character varying(64) NOT NULL, application_id character varying(64), citizen_id character varying(64) NOT NULL, service_id character varying(64), amount numeric(12, 2) NOT NULL, currency character varying(3) NOT NULL DEFAULT 'USD', payment_method character varying(50), payment_provider_reference character varying(128), payment_timestamp timestamp NOT NULL, status character varying(30) NOT NULL, notes text, PRIMARY KEY (payment_id) )
CREATE TABLE government_services.employees ( employee_id character varying(64) NOT NULL, agency_id character varying(64) NOT NULL, first_name character varying(100) NOT NULL, last_name character varying(100) NOT NULL, job_title character varying(150) NOT NULL, department character varying(100), work_email character varying(128) NOT NULL UNIQUE, work_phone character varying(32), hire_date date NOT NULL, termination_date date, access_level character varying(50), manager_employee_id character varying(64), PRIMARY KEY (employee_id) )
CREATE TABLE government_services.notifications ( notification_id character varying(64) NOT NULL, citizen_id character varying(64) NOT NULL, application_id character varying(64), message_subject character varying(255), message_body text NOT NULL, channel character varying(30) NOT NULL, sent_at timestamp NOT NULL, status character varying(30) NOT NULL, related_entity_type character varying(50), related_entity_id character varying(64), PRIMARY KEY (notification_id) )
##Table Structure
CREATE TABLE legal_services.time_entries (
    entry_id character varying(64) NOT NULL,  -- unique identifier for the time entry
    case_id character varying(64) NOT NULL, -- FK to cases table
    lawyer_id character varying(64) NOT NULL, -- FK to lawyers table (who performed the work)
    date_worked date NOT NULL, -- date the work was performed
    hours_spent numeric(5, 2) NOT NULL CHECK (hours_spent > 0), -- duration of work in hours (e.g., 1.5 for 1h 30m)
    billing_rate numeric(10, 2) NOT NULL, -- hourly rate applied for this entry
    description text NOT NULL, -- detailed description of the work performed
    is_billable boolean DEFAULT true, -- whether this time entry is billable to the client
    is_billed boolean DEFAULT false, -- whether this entry has been included in an invoice
    invoice_id character varying(64), -- FK to invoices table (once billed)
    created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, -- when the entry was recorded
    PRIMARY KEY (entry_id)
)
##Table Structure
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 )
##Table Structure
CREATE TABLE insurance.policy_beneficiaries ( beneficiary_id text, policy_id text, customer_id text, first_name text, last_name text, relationship text, percentage_share numeric, contact_info text, added_at timestamp )

[User] Show me all servers in the same region that have different statuses. I want to see the server names, regions, and their statuses for each pair.

[Assistant]
SELECT s1.server_name AS server1, s2.server_name AS server2, s1.region, s1.status AS status1, s2.status AS status2
FROM gaming_technology.servers s1
JOIN gaming_technology.servers s2
  ON s1.region = s2.region
  AND s1.server_id <> s2.server_id
  AND s1.status <> s2.status;

[User] Please also include the current_players of both servers in the result.

[Assistant]
SELECT s1.server_name AS server1, s2.server_name AS server2, s1.region, s1.status AS status1, s2.status AS status2, s1.current_players AS server1_current_players, s2.current_players AS server2_current_players
FROM gaming_technology.servers s1
JOIN gaming_technology.servers s2
  ON s1.region = s2.region
  AND s1.server_id <> s2.server_id
  AND s1.status <> s2.status;

[User] Retrieve each employee's first and last name along with the count of applications they've been assigned that are currently in the 'Under Review' status.

[Assistant]
SELECT e.first_name,
       e.last_name,
       COUNT(app.application_id) AS under_review_count
FROM government_services.employees e
LEFT JOIN government_services.applications app ON e.employee_id = app.assigned_employee_id
    AND app.status = 'Under Review'
GROUP BY e.employee_id, e.first_name, e.last_name;

[User] Show me the total number of time entries for each case.

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

[User] Only include cases where the total is greater than 10.

[Assistant]
SELECT case_id, COUNT(*) AS entry_count
FROM legal_services.time_entries
GROUP BY case_id
HAVING COUNT(*) > 10;

[User] Count the number of securities and the number of distinct issuers for each sector.

[Assistant] SELECT sector, COUNT(*) AS securities_count, COUNT(DISTINCT issuer_name) AS distinct_issuer_count FROM financial_services.securities GROUP BY sector;

[User] Exclude any sector that has fewer than 5 securities.

[Assistant] SELECT sector, COUNT(*) AS securities_count, COUNT(DISTINCT issuer_name) AS distinct_issuer_count FROM financial_services.securities GROUP BY sector HAVING COUNT(*) >= 5;

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

[Assistant] SELECT sector, COUNT(*) AS securities_count, COUNT(DISTINCT issuer_name) AS distinct_issuer_count FROM financial_services.securities GROUP BY sector HAVING COUNT(*) >= 5 ORDER BY securities_count DESC;

[User] List all beneficiaries who have a relationship of 'Parent' and a percentage_share less than 25%. Show their beneficiary_id, first_name, last_name, relationship, and percentage_share.

[Assistant]
SELECT beneficiary_id, first_name, last_name, relationship, percentage_share
FROM insurance.policy_beneficiaries
WHERE relationship = 'Parent' AND percentage_share < 25;


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.accounts ( account_id text PRIMARY KEY, customer_id text, account_number text, account_type text, balance numeric, currency text, opened_date date, status text, interest_rate numeric, last_updated_at timestamp )
CREATE TABLE financial_services.transactions ( transaction_id text PRIMARY KEY, account_id text, related_account_id text, transaction_type text, amount numeric, currency text, transaction_date timestamp, effective_date date, description text, status text, reference_number text )
CREATE TABLE financial_services.securities ( security_id text PRIMARY KEY, 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.trades ( trade_id text PRIMARY KEY, account_id text, security_id text, order_id text, trade_type text, quantity numeric, price_per_unit numeric, total_amount numeric, commission numeric, trade_timestamp timestamp, settlement_date date, status text, execution_venue text )
CREATE TABLE financial_services.market_data ( data_point_id bigserial PRIMARY KEY, security_id text, data_timestamp timestamp, open_price numeric, high_price numeric, low_price numeric, close_price numeric, adjusted_close_price numeric, volume bigint, source text )
CREATE TABLE financial_services.employees ( employee_id text PRIMARY KEY, first_name text, last_name text, job_title text, department text, branch_id text, email text, phone_extension text, hire_date date, termination_date date, manager_id text, status text )
CREATE TABLE financial_services.loans ( loan_id text PRIMARY KEY, account_id text, loan_type text, principal_amount numeric, current_principal_balance numeric, interest_rate numeric, term_months int, origination_date date, maturity_date date, monthly_payment numeric, collateral_description text, status text )
##Table Structure
CREATE TABLE legal_services.clients (
    client_id character varying(64) NOT NULL,  -- unique identifier for the client
    first_name character varying(100) NOT NULL, -- client's first name
    last_name character varying(100) NOT NULL, -- client's last name
    company_name character varying(200), -- company name if applicable
    email character varying(128) UNIQUE NOT NULL, -- client's primary email
    phone character varying(32), -- client's contact phone number
    address text, -- client's full address
    date_registered timestamp NOT NULL, -- when the client was first registered
    status character varying(32) NOT NULL, -- client status (e.g., active, inactive, prospect)
    PRIMARY KEY (client_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.appointments (
    appointment_id character varying(64) NOT NULL, -- unique identifier for the appointment
    client_id character varying(64) NOT NULL, -- FK to clients table
    lawyer_id character varying(64) NOT NULL, -- FK to lawyers table
    case_id character varying(64), -- FK to cases table (optional, if related to a specific case)
    start_time timestamp NOT NULL, -- scheduled start date and time
    end_time timestamp NOT NULL, -- scheduled end date and time
    location text, -- location of the meeting (address or virtual link)
    subject character varying(255), -- subject or purpose of the appointment
    notes text, -- additional notes for the appointment
    status character varying(50) NOT NULL, -- e.g., Scheduled, Completed, Canceled, Rescheduled
    created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
    PRIMARY KEY (appointment_id)
)
##Table Structure
CREATE TABLE government_services.services ( service_id character varying(64) NOT NULL, agency_id character varying(64) NOT NULL, service_name character varying(255) NOT NULL, description text, category character varying(100), eligibility_criteria text, standard_fee numeric(10, 2) DEFAULT 0.00, average_processing_time_days integer, is_active boolean DEFAULT true, online_application_url character varying(255), PRIMARY KEY (service_id) )
CREATE TABLE government_services.applications ( application_id character varying(64) NOT NULL, citizen_id character varying(64) NOT NULL, service_id character varying(64) NOT NULL, submitted_at timestamp NOT NULL, status character varying(50) NOT NULL, last_updated_at timestamp NOT NULL, assigned_employee_id character varying(64), decision_date date, notes text, reference_number character varying(100) UNIQUE, PRIMARY KEY (application_id) )
CREATE TABLE government_services.documents ( document_id 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 character varying(64) NOT NULL, agency_id character varying(64) NOT NULL, first_name character varying(100) NOT NULL, last_name character varying(100) NOT NULL, job_title character varying(150) NOT NULL, department character varying(100), work_email character varying(128) NOT NULL UNIQUE, work_phone character varying(32), hire_date date NOT NULL, termination_date date, access_level character varying(50), manager_employee_id character varying(64), PRIMARY KEY (employee_id) )
CREATE TABLE government_services.appointments ( appointment_id character varying(64) NOT NULL, citizen_id character varying(64) NOT NULL, employee_id character varying(64), location_id character varying(64), service_id character varying(64), scheduled_start_time timestamp NOT NULL, scheduled_end_time timestamp, purpose text NOT NULL, status character varying(30) NOT NULL, booking_method character varying(50), created_at timestamp NOT NULL, notes text, PRIMARY KEY (appointment_id) )
##Table Structure
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 )

[User] Summarize the trades by trade type, showing the total quantity and the total amount for each type.

[Assistant] SELECT trade_type, SUM(quantity) AS total_quantity, SUM(total_amount) AS total_amount FROM financial_services.trades GROUP BY trade_type;

[User] Calculate the total sum of hours spent across all time entries that are billable but have not yet been billed.

[Assistant] SELECT SUM(hours_spent) FROM legal_services.time_entries WHERE is_billable = TRUE AND is_billed = FALSE;

[User] Which employees have verified more than 5 documents in the last 30 days? Return the employee's full name, department, and the number of verifications.

[Assistant]
SELECT e.first_name || ' ' || e.last_name AS full_name, e.department, COUNT(d.document_id) AS verification_count
FROM government_services.documents d
JOIN government_services.employees e ON d.verified_by_employee_id = e.employee_id
WHERE d.verification_status = 'Verified'
  AND d.verification_timestamp >= now() - interval '30 days'
GROUP BY e.first_name, e.last_name, e.department
HAVING COUNT(d.document_id) > 5;

[User] How many securities are there for each security type?

[Assistant] SELECT security_type, COUNT(*) AS security_count FROM financial_services.securities GROUP BY security_type;

[User] Only show security types that have more than 50 securities.

[Assistant] SELECT security_type, COUNT(*) AS security_count FROM financial_services.securities GROUP BY security_type HAVING COUNT(*) > 50;

[User] Sort the result by the count in descending order.

[Assistant] SELECT security_type, COUNT(*) AS security_count FROM financial_services.securities GROUP BY security_type HAVING COUNT(*) > 50 ORDER BY security_count DESC;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement. ##Table Structure
CREATE TABLE 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.assets ( asset_id text, name text, symbol text, type text )
CREATE TABLE trading_platform.dapps ( dapp_id text, name text, description text, url text )
CREATE TABLE trading_platform.peers ( peer_id text, ip_address text, port integer, last_seen timestamp )
CREATE TABLE trading_platform.metadata ( metadata_id text, asset_id text, key text, value text )
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, 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 gaming_technology.achievements ( achievement_id.uuid, game_id.uuid, name.text, description.text, icon_url.text, points.integer, hidden.boolean )
CREATE TABLE gaming_technology.player_achievements ( player_achievement_id.uuid, player_id.uuid, achievement_id.uuid, unlocked_at.timestamptz )
CREATE TABLE gaming_technology.player_inventory ( inventory_id.uuid, player_id.uuid, item_id.uuid, quantity.integer, acquired_at.timestamptz, instance_data.jsonb )
##Table Structure
CREATE TABLE insurance.policies ( policy_id character varying(64) NOT NULL, customer_id character varying(64) NOT NULL, product_id character varying(64) NOT NULL, agent_id character varying(64), policy_number character varying(100) NOT NULL UNIQUE, start_date date NOT NULL, end_date date NOT NULL, premium_amount numeric(12, 2) NOT NULL, coverage_limit numeric(15, 2) NOT NULL, deductible numeric(10, 2) NOT NULL, status character varying(30) NOT NULL, issued_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, cancellation_date date, cancellation_reason text, PRIMARY KEY (policy_id) )
CREATE TABLE insurance.claims ( claim_id character varying(64) NOT NULL, policy_id character varying(64) NOT NULL, customer_id character varying(64) NOT NULL, incident_date timestamp NOT NULL, reported_date timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, description text NOT NULL, estimated_loss numeric(15, 2), status character varying(30) NOT NULL, settlement_amount numeric(15, 2), settlement_date date, claim_handler_id character varying(64), police_report_number character varying(100), PRIMARY KEY (claim_id) )
CREATE TABLE insurance.insurance_products ( product_id character varying(64) NOT NULL, product_name character varying(150) NOT NULL, product_type character varying(50) NOT NULL, description text, base_premium numeric(10, 2) NOT NULL, coverage_details text, underwriting_rules text, is_active boolean NOT NULL DEFAULT true, created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, updated_at timestamp, PRIMARY KEY (product_id) )
CREATE TABLE insurance.claim_documents ( document_id character varying(64) NOT NULL, claim_id character varying(64) NOT NULL, document_type character varying(50) NOT NULL, file_name character varying(255) NOT NULL, file_path character varying(512) NOT NULL, file_size_bytes integer, mime_type character varying(100), uploaded_by character varying(64), uploaded_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, description text, PRIMARY KEY (document_id) )
##Table Structure
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 )
##Table Structure
CREATE TABLE healthcare.patient_insurance (
    patient_insurance_id character varying(64) NOT NULL, -- unique identifier for this patient-plan link
    patient_id character varying(64) NOT NULL, -- FK to patients table
    plan_id character varying(64) NOT NULL, -- FK to insurance_plans table
    policy_number character varying(100) NOT NULL, -- patient's policy number
    group_number character varying(100), -- group number, if applicable
    subscriber_name character varying(200), -- name of the primary policy holder
    effective_date date NOT NULL, -- date the coverage begins
    expiration_date date, -- date the coverage ends (if known)
    is_primary boolean NOT NULL DEFAULT true, -- indicates if this is the primary insurance
    PRIMARY KEY (patient_insurance_id),
    UNIQUE (patient_id, plan_id, policy_number) -- ensure a patient doesn't have the same policy twice
)

[User] List the asset names and symbols for all assets of type 'token'.

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

[User] Find all pairs of achievement unlocks and item acquisitions by the same player where the item was acquired after the achievement was unlocked. List player_id, achievement_id, unlocked_at, item_id, and acquired_at.

[Assistant] SELECT pa.player_id, pa.achievement_id, pa.unlocked_at, pi.item_id, pi.acquired_at FROM gaming_technology.player_achievements pa JOIN gaming_technology.player_inventory pi ON pa.player_id = pi.player_id WHERE pi.acquired_at > pa.unlocked_at;

[User] Only include pairs where the item acquisition happened within 24 hours after the achievement unlock.

[Assistant] SELECT pa.player_id, pa.achievement_id, pa.unlocked_at, pi.item_id, pi.acquired_at FROM gaming_technology.player_achievements pa JOIN gaming_technology.player_inventory pi ON pa.player_id = pi.player_id WHERE pi.acquired_at > pa.unlocked_at AND pi.acquired_at <= pa.unlocked_at + INTERVAL '24 hours';

[User] List all insurance products along with their product type and creation date.

[Assistant]
SELECT product_name, product_type, created_at
FROM insurance.insurance_products;

[User] Show me pairs of invoice numbers for the same case.

[Assistant] SELECT T1.invoice_number, T2.invoice_number, T1.case_id FROM legal_services.invoices AS T1 JOIN legal_services.invoices AS T2 ON T1.case_id = T2.case_id AND T1.invoice_id <> T2.invoice_id ORDER BY T1.case_id, T1.invoice_number, T2.invoice_number

[User] Only include pairs where the total amount of one invoice is greater than the other.

[Assistant] SELECT T1.invoice_number, T2.invoice_number, T1.case_id, T1.total_amount AS invoice1_amount, T2.total_amount AS invoice2_amount FROM legal_services.invoices AS T1 JOIN legal_services.invoices AS T2 ON T1.case_id = T2.case_id AND T1.invoice_id <> T2.invoice_id WHERE T1.total_amount > T2.total_amount ORDER BY T1.case_id, invoice1_amount DESC

[User] Exclude pairs where the issue dates are more than 90 days apart.

[Assistant] SELECT T1.invoice_number, T2.invoice_number, T1.case_id, T1.total_amount AS invoice1_amount, T2.total_amount AS invoice2_amount, ABS(DATE_PART('day', T1.issue_date - T2.issue_date)) AS days_apart FROM legal_services.invoices AS T1 JOIN legal_services.invoices AS T2 ON T1.case_id = T2.case_id AND T1.invoice_id <> T2.invoice_id WHERE T1.total_amount > T2.total_amount AND ABS(DATE_PART('day', T1.issue_date - T2.issue_date)) <= 90 ORDER BY T1.case_id, days_apart ASC

[User] Can you list all the policy numbers and their group_numbers for policies that will expire within the next 90 days from today?

[Assistant] SELECT policy_number, group_number FROM healthcare.patient_insurance WHERE expiration_date BETWEEN CURRENT_DATE AND CURRENT_DATE + INTERVAL '90 days';

[User] Only show results where the group_number is not null.

[Assistant] SELECT policy_number, group_number FROM healthcare.patient_insurance WHERE expiration_date BETWEEN CURRENT_DATE AND CURRENT_DATE + INTERVAL '90 days' AND group_number IS NOT NULL;