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.text, case_id.text, document_name.text, document_type.text, storage_path.text, uploaded_by_lawyer_id.text, upload_timestamp.timestamp, version.integer, description.text )
##Table Structure
CREATE TABLE social_media.conversations ( conversation_id character varying(64) NOT NULL, created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, last_message_at timestamp, is_group_chat boolean NOT NULL DEFAULT false, group_name character varying(100), PRIMARY KEY (conversation_id) )
##Table Structure
CREATE TABLE transportation.drivers ( driver_id character varying(64) NOT NULL, employee_id character varying(64) NOT NULL UNIQUE, first_name character varying(128) NOT NULL, last_name character varying(128) NOT NULL, license_number character varying(64) NOT NULL UNIQUE, license_expiry_date date NOT NULL, contact_number character varying(32), email character varying(128) UNIQUE, hire_date date NOT NULL, status character varying(32) NOT NULL, PRIMARY KEY (driver_id) )
CREATE TABLE transportation.routes ( route_id character varying(64) NOT NULL, route_number character varying(32) NOT NULL UNIQUE, description text, origin_location_id character varying(64) NOT NULL, destination_location_id character varying(64) NOT NULL, distance_km numeric(10, 2), estimated_duration_minutes integer, type character varying(32) NOT NULL, PRIMARY KEY (route_id) )
CREATE TABLE transportation.locations ( location_id character varying(64) NOT NULL, name character varying(255) NOT NULL, type character varying(64) NOT NULL, address_line1 character varying(255), city character varying(128), state_province character varying(128), postal_code character varying(32), country character varying(64) NOT NULL, latitude numeric(9, 6), longitude numeric(9, 6), timezone character varying(64), PRIMARY KEY (location_id) )
CREATE TABLE transportation.passengers ( passenger_id character varying(64) NOT NULL, first_name character varying(128) NOT NULL, last_name character varying(128) NOT NULL, email character varying(128) UNIQUE, phone_number character varying(32) UNIQUE, date_of_birth date, loyalty_program_id character varying(64), created_at timestamp with time zone NOT NULL, PRIMARY KEY (passenger_id) )
##Table Structure
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 healthcare.medical_records ( record_id text, patient_id text, appointment_id text, doctor_id text, record_date timestamp, chief_complaint text, present_illness_history text, past_medical_history text, physical_examination_notes text, assessment text, treatment_plan text, vitals text, created_at timestamp )

[User] List the latest version of each document (identified by case_id and document_name), showing the version number and its upload_timestamp.

[Assistant]
SELECT d.case_id,
       d.document_name,
       d.version   AS latest_version,
       d.upload_timestamp
FROM legal_services.documents d
JOIN (
  SELECT case_id, document_name, MAX(version) AS max_version
  FROM legal_services.documents
  GROUP BY case_id, document_name
) m ON d.case_id = m.case_id
    AND d.document_name = m.document_name
    AND d.version = m.max_version;

[User] Actually, I also want to see the upload_timestamp of the previous version for each document.

[Assistant]
SELECT m.case_id,
       m.document_name,
       m.max_version         AS latest_version,
       d_latest.upload_timestamp  AS latest_timestamp,
       d_prev.upload_timestamp    AS previous_timestamp
FROM (
  SELECT case_id, document_name, MAX(version) AS max_version
  FROM legal_services.documents
  GROUP BY case_id, document_name
) m
JOIN legal_services.documents d_latest
  ON d_latest.case_id = m.case_id
 AND d_latest.document_name = m.document_name
 AND d_latest.version = m.max_version
LEFT JOIN legal_services.documents d_prev
  ON d_prev.case_id = m.case_id
 AND d_prev.document_name = m.document_name
 AND d_prev.version = m.max_version - 1;

[User] Also, only include documents whose first version (version = 1) was uploaded in 2024.

[Assistant]
SELECT m.case_id,
       m.document_name,
       m.max_version          AS latest_version,
       d_latest.upload_timestamp   AS latest_timestamp,
       d_prev.upload_timestamp     AS previous_timestamp
FROM (
  SELECT case_id, document_name, MAX(version) AS max_version
  FROM legal_services.documents
  GROUP BY case_id, document_name
) m
JOIN legal_services.documents d_first
  ON d_first.case_id = m.case_id
 AND d_first.document_name = m.document_name
 AND d_first.version = 1
 AND d_first.upload_timestamp >= '2024-01-01'
 AND d_first.upload_timestamp < '2025-01-01'
JOIN legal_services.documents d_latest
  ON d_latest.case_id = m.case_id
 AND d_latest.document_name = m.document_name
 AND d_latest.version = m.max_version
LEFT JOIN legal_services.documents d_prev
  ON d_prev.case_id = m.case_id
 AND d_prev.document_name = m.document_name
 AND d_prev.version = m.max_version - 1;

[User] For each group chat, list its ID, name, creation time, and the creation time of the next group chat created after it, ordered by creation time.

[Assistant] SELECT conversation_id, group_name, created_at, LEAD(created_at) OVER (ORDER BY created_at) AS next_group_chat_created_at FROM social_media.conversations WHERE is_group_chat = true ORDER BY created_at;

[User] Only show pairs where the next group chat was created within 48 hours of the current one, and also include the time difference in hours.

[Assistant] WITH RankedGroupChats AS ( SELECT conversation_id, group_name, created_at, LEAD(created_at) OVER (ORDER BY created_at) AS next_group_chat_created_at FROM social_media.conversations WHERE is_group_chat = true ) SELECT conversation_id, group_name, created_at, next_group_chat_created_at, EXTRACT(EPOCH FROM (next_group_chat_created_at - created_at)) / 3600 AS time_difference_hours FROM RankedGroupChats WHERE next_group_chat_created_at IS NOT NULL AND EXTRACT(EPOCH FROM (next_group_chat_created_at - created_at)) <= 48 * 3600 ORDER BY created_at;

[User] Further refine: Only include group chats whose names contain 'Discuss'.

[Assistant] WITH RankedGroupChats AS ( SELECT conversation_id, group_name, created_at, LEAD(created_at) OVER (ORDER BY created_at) AS next_group_chat_created_at FROM social_media.conversations WHERE is_group_chat = true ) SELECT conversation_id, group_name, created_at, next_group_chat_created_at, EXTRACT(EPOCH FROM (next_group_chat_created_at - created_at)) / 3600 AS time_difference_hours FROM RankedGroupChats WHERE next_group_chat_created_at IS NOT NULL AND EXTRACT(EPOCH FROM (next_group_chat_created_at - created_at)) <= 48 * 3600 AND group_name LIKE '%Discuss%' ORDER BY created_at;

[User] List all locations that serve as either an origin or a destination in any route, including the location name, city, number of routes starting there (origin_count), and number of routes ending there (destination_count).

[Assistant] SELECT l.location_id, l.name, l.city, COALESCE(o.origin_count, 0) AS origin_count, COALESCE(d.dest_count, 0) AS destination_count FROM transportation.locations l LEFT JOIN (SELECT origin_location_id AS location_id, COUNT(*) AS origin_count FROM transportation.routes GROUP BY origin_location_id) o ON l.location_id = o.location_id LEFT JOIN (SELECT destination_location_id AS location_id, COUNT(*) AS dest_count FROM transportation.routes GROUP BY destination_location_id) d ON l.location_id = d.location_id WHERE COALESCE(o.origin_count, 0) > 0 OR COALESCE(d.dest_count, 0) > 0;

[User] Which users have disabled both email and push notifications? Please provide their user IDs and whether their profiles are private.

[Assistant] SELECT user_id, private_profile FROM social_media.user_settings WHERE email_notifications_enabled = FALSE AND push_notifications_enabled = FALSE;

[User] Also, only include those users who have updated their settings in the last 60 days.

[Assistant] SELECT user_id, private_profile FROM social_media.user_settings WHERE email_notifications_enabled = FALSE AND push_notifications_enabled = FALSE AND updated_at >= NOW() - INTERVAL '60 days';

[User] Count the total number of medical records where both assessment and treatment_plan fields are provided.

[Assistant]
SELECT COUNT(*) AS total_records
FROM healthcare.medical_records
WHERE assessment IS NOT NULL AND treatment_plan IS NOT NULL;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement. ##Table Structure
CREATE TABLE government_services.citizens ( citizen_id.text, national_id_number.text, first_name.text, last_name.text, date_of_birth.date, gender.text, primary_address.text, contact_email.text, contact_phone.text, registration_date.timestamp, is_verified.boolean )
CREATE TABLE government_services.agencies ( agency_id.text, agency_name.text, jurisdiction_level.text, primary_contact_email.text, main_phone_number.text, website_url.text, established_date.date, parent_agency_id.text )
CREATE TABLE government_services.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.employees ( employee_id.text, agency_id.text, first_name.text, last_name.text, job_title.text, department.text, work_email.text, work_phone.text, hire_date.date, termination_date.date, access_level.text, manager_employee_id.text )
CREATE TABLE government_services.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 healthcare.patients ( patient_id.text, first_name.text, last_name.text, date_of_birth.date, gender.text, address.text, phone_number.text, email.text, emergency_contact_name.text, emergency_contact_phone.text, created_at.timestamp, updated_at.timestamp )
CREATE TABLE healthcare.appointments ( appointment_id.text, patient_id.text, doctor_id.text, appointment_time.timestamp, duration_minutes.integer, reason.text, status.text, location_id.text, notes.text, created_at.timestamp )
##Table Structure
CREATE TABLE hospitality_technology.properties ( property_id character varying(64) NOT NULL, property_name character varying(255) NOT NULL, address_line1 character varying(255) NOT NULL, address_line2 character varying(255), city character varying(100) NOT NULL, state_province character varying(100), postal_code character varying(20) NOT NULL, country_code character varying(3) NOT NULL, phone_number character varying(30), email_address character varying(255), property_type character varying(50) NOT NULL, star_rating numeric(2,1), timezone character varying(64) NOT NULL, manager_staff_id character varying(64), created_at timestamp with time zone NOT NULL DEFAULT current_timestamp, updated_at timestamp with time zone NOT NULL DEFAULT current_timestamp, PRIMARY KEY (property_id) )
CREATE TABLE hospitality_technology.rooms (
    room_id character varying(64) NOT NULL,  -- unique identifier for the room
    property_id character varying(64) NOT NULL, -- FK to properties table
    room_number character varying(10) NOT NULL, -- room number identifier (e.g., '101', 'Suite 2B')
    room_type_id character varying(64) NOT NULL, -- FK to room_types table
    floor integer, -- floor number the room is on
    status character varying(50) NOT NULL, -- e.g., Available, Occupied, Cleaning, OutOfOrder, Maintenance
    is_smoking boolean NOT NULL DEFAULT false, -- smoking allowed flag
    features text, -- description of features (e.g., Balcony, Sea View, Jacuzzi)
    current_condition text, -- notes on room condition
    last_cleaned_at timestamp with time zone, -- timestamp of last cleaning
    PRIMARY KEY (room_id),
    FOREIGN KEY (property_id) REFERENCES hospitality_technology.properties(property_id),
    FOREIGN KEY (room_type_id) REFERENCES hospitality_technology.room_types(room_type_id)
)
CREATE TABLE hospitality_technology.room_types ( room_type_id.text, property_id.text, type_name.text, description.text, base_rate.numeric, max_occupancy.integer, 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.services ( service_id character varying(64) NOT NULL, property_id character varying(64) NOT NULL, service_name character varying(150) NOT NULL, description text, category character varying(100), price numeric(10, 2) NOT NULL, unit character varying(30), is_available boolean NOT NULL DEFAULT true, department character varying(100), PRIMARY KEY (service_id), FOREIGN KEY (property_id) REFERENCES hospitality_technology.properties(property_id) )
CREATE TABLE hospitality_technology.payments ( payment_id.text, reservation_id.text, guest_id.text, bill_id.text, amount.numeric, currency_code.text, payment_method.text, card_type.text, card_last_four.text, transaction_ref.text, payment_timestamp.timestamp, status.text, staff_id_processed.text, notes.text )
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 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.utxos ( utxo_id text, transaction_id text, output_index integer, address text, amount numeric, spent boolean )
CREATE TABLE trading_platform.dapps ( dapp_id text, name text, description text, url text )
CREATE TABLE trading_platform.peers ( peer_id text, ip_address text, port integer, last_seen timestamp )
CREATE TABLE trading_platform.metadata ( metadata_id text, asset_id text, key text, value text )
CREATE TABLE trading_platform.logs ( log_id text, user_id text, action text, details text, logged_at timestamp )

[User] Show the full names and contact emails of all citizens who have made payments for applications assigned to employees with the job title 'Supervisor'.

[Assistant]
SELECT DISTINCT c.first_name || ' ' || c.last_name AS full_name, c.contact_email
FROM government_services.citizens c
JOIN government_services.payments p ON c.citizen_id = p.citizen_id
JOIN government_services.applications a ON p.application_id = a.application_id
JOIN government_services.employees e ON a.assigned_employee_id = e.employee_id
WHERE e.job_title = 'Supervisor';

[User] Retrieve the patient_id, first_name, last_name, and email for all patients who do not have an emergency contact phone number.

[Assistant]
SELECT patient_id, first_name, last_name, email
FROM healthcare.patients
WHERE emergency_contact_phone IS NULL;

[User] Get each property's name, manager_staff_id, and the number of rooms with status 'OutOfOrder', including properties with zero OutOfOrder rooms.

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

[User] List all assets with their name, symbol, and type where the asset type is 'token'.

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


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 )
##Table Structure
CREATE TABLE hospitality_technology.guests ( guest_id.text, first_name.text, last_name.text, email.text, phone_number.text, date_of_birth.date, address_line1.text, city.text, state_province.text, postal_code.text, country_code.text, preferences.text, loyalty_member_id.text, communication_consent.boolean, created_at.timestamp, updated_at.timestamp )
##Table Structure
CREATE TABLE transportation.trips (
    trip_id character varying(64) NOT NULL,  -- unique identifier for a specific trip instance
    route_id character varying(64), -- identifier of the route being followed (can be null for ad-hoc trips)
    vehicle_id character varying(64) NOT NULL, -- identifier of the vehicle used
    driver_id character varying(64) NOT NULL, -- identifier of the driver operating
    scheduled_departure timestamp with time zone NOT NULL, -- planned departure time
    actual_departure timestamp with time zone, -- actual departure time
    scheduled_arrival timestamp with time zone NOT NULL, -- planned arrival time
    actual_arrival timestamp with time zone, -- actual arrival time
    origin_location_id character varying(64) NOT NULL, -- actual starting location (could differ from route origin)
    destination_location_id character varying(64) NOT NULL, -- actual ending location (could differ from route destination)
    status character varying(32) NOT NULL, -- e.g., Scheduled, In Progress, Completed, Delayed, Cancelled
    passenger_count integer, -- number of passengers (if applicable)
    cargo_manifest_id character varying(64), -- link to cargo details (if applicable)
    PRIMARY KEY (trip_id)
)
##Table Structure
CREATE TABLE legal_services.clients ( client_id text PRIMARY KEY, first_name text, last_name text, company_name text, email text UNIQUE, phone text, address text, date_registered timestamp, status text )
CREATE TABLE legal_services.invoices ( invoice_id text, invoice_number text, 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 blockchain.transactions (
    transaction_id character varying(64) NOT NULL,  -- unique identifier for the transaction
    block_id character varying(64) NOT NULL, -- identifier of the block containing the transaction
    sender_address character varying(128) NOT NULL, -- address of the sender
    receiver_address character varying(128) NOT NULL, -- address of the receiver
    amount numeric(38,14) NOT NULL, -- amount transferred
    timestamp timestamp NOT NULL, -- time when the transaction was created
    signature text NOT NULL, -- digital signature of the transaction
    PRIMARY KEY (transaction_id)
)

[User] List peer IDs and IP addresses for all peers whose IP address starts with '10.'.

[Assistant] SELECT peer_id, ip_address FROM trading_platform.peers WHERE ip_address LIKE '10.%';

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

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

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

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

[User] Show me the count of trips by status for each vehicle, but only include vehicles that have had more than 5 trips total.

[Assistant] SELECT vehicle_id, status, COUNT(*) as trip_count FROM transportation.trips GROUP BY vehicle_id, status HAVING COUNT(*) > 5;

[User] Now filter this to only show vehicles that have had at least 2 cancelled trips.

[Assistant] SELECT vehicle_id, COUNT(*) as cancelled_trips FROM transportation.trips WHERE status = 'Cancelled' GROUP BY vehicle_id HAVING COUNT(*) >= 2;

[User] Combine both queries to show me vehicles with more than 5 total trips and at least 2 cancelled trips, along with their complete status distribution.

[Assistant] SELECT t.vehicle_id, t.status, COUNT(*) as trip_count FROM transportation.trips t JOIN (SELECT vehicle_id FROM transportation.trips GROUP BY vehicle_id HAVING COUNT(*) > 5 INTERSECT SELECT vehicle_id FROM transportation.trips WHERE status = 'Cancelled' GROUP BY vehicle_id HAVING COUNT(*) >= 2) v ON t.vehicle_id = v.vehicle_id GROUP BY t.vehicle_id, t.status;

[User] Show me a list of all clients and their invoices, including the client's full name, email, invoice number, total amount, and invoice status.

[Assistant]
SELECT c.first_name, c.last_name, c.email, i.invoice_number, i.total_amount, i.status
FROM legal_services.clients c
LEFT JOIN legal_services.invoices i ON c.client_id = i.client_id;

[User] Can you update the query to include only those invoices with a total amount greater than 2,000?

[Assistant]
SELECT c.first_name, c.last_name, c.email, i.invoice_number, i.total_amount, i.status
FROM legal_services.clients c
LEFT JOIN legal_services.invoices i ON c.client_id = i.client_id
WHERE i.total_amount > 2000;

[User] Actually, I want to see only clients who have at least two such invoices. Can you modify the query to reflect that?

[Assistant]
SELECT c.first_name, c.last_name, c.email, i.invoice_number, i.total_amount, i.status
FROM legal_services.clients c
JOIN (
    SELECT client_id
    FROM legal_services.invoices
    WHERE total_amount > 2000
    GROUP BY client_id
    HAVING COUNT(*) >= 2
) filtered_clients ON c.client_id = filtered_clients.client_id
JOIN legal_services.invoices i ON c.client_id = i.client_id AND i.total_amount > 2000;

[User] Find all pairs of transactions where the sender address and the receiver address are the same, but the transactions occurred on different days. Show transaction IDs, addresses, and their timestamps.

[Assistant]
SELECT t1.transaction_id AS tx1_id, t2.transaction_id AS tx2_id, t1.sender_address, t1.timestamp AS tx1_time, t2.timestamp AS tx2_time
FROM blockchain.transactions t1
JOIN blockchain.transactions t2
  ON t1.sender_address = t2.sender_address
 AND t1.receiver_address = t2.receiver_address
 AND t1.transaction_id <> t2.transaction_id
 AND DATE(t1.timestamp) <> DATE(t2.timestamp)
WHERE t1.sender_address = t1.receiver_address;

[User] Exclude pairs where the two transactions happened more than 7 days apart.

[Assistant]
SELECT t1.transaction_id AS tx1_id, t2.transaction_id AS tx2_id, t1.sender_address, t1.timestamp AS tx1_time, t2.timestamp AS tx2_time
FROM blockchain.transactions t1
JOIN blockchain.transactions t2
  ON t1.sender_address = t2.sender_address
 AND t1.receiver_address = t2.receiver_address
 AND t1.transaction_id <> t2.transaction_id
 AND DATE(t1.timestamp) <> DATE(t2.timestamp)
WHERE t1.sender_address = t1.receiver_address
  AND ABS(DATE_PART('day', t1.timestamp - t2.timestamp)) <= 7;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement. ##Table Structure
CREATE TABLE transportation.vehicles ( vehicle_id text PRIMARY KEY, license_plate text, vin text, make text, model text, year int, type text, capacity int, fuel_type text, status text, depot_id text, acquisition_date date )
CREATE TABLE transportation.locations ( location_id text, name text, type text, address_line1 text, city text, state_province text, postal_code text, country text, latitude numeric, longitude numeric, timezone text )
CREATE TABLE transportation.passengers (
    passenger_id character varying(64) NOT NULL,  -- unique identifier for the passenger
    first_name character varying(128) NOT NULL, -- passenger's first name
    last_name character varying(128) NOT NULL, -- passenger's last name
    email character varying(128) UNIQUE, -- email address
    phone_number character varying(32) UNIQUE, -- phone number
    date_of_birth date, -- passenger's date of birth
    loyalty_program_id character varying(64), -- identifier for loyalty program membership
    created_at timestamp with time zone NOT NULL, -- time when the passenger record was created
    PRIMARY KEY (passenger_id)
)
CREATE TABLE transportation.bookings ( booking_id character varying(64) NOT NULL, passenger_id character varying(64) NOT NULL, trip_id character varying(64) NOT NULL, seat_number character varying(16), booking_time timestamp with time zone NOT NULL, status character varying(32) NOT NULL, fare numeric(10, 2) NOT NULL, payment_transaction_id character varying(128), special_requests text, PRIMARY KEY (booking_id) )
##Table Structure
CREATE TABLE 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 )
##Table Structure
CREATE TABLE gaming_technology.developers ( developer_id uuid, name text, country text, founded_year integer, website text, created_at timestamp with time zone )
##Table Structure
CREATE TABLE insurance.insurance_products ( product_id text PRIMARY KEY, product_name text, product_type text, description text, base_premium numeric, coverage_details text, underwriting_rules text, is_active boolean, created_at timestamp, updated_at timestamp )
##Table Structure
CREATE TABLE trading_platform.users ( user_id.text, username.text, email.text, password_hash.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.utxos ( utxo_id.text, transaction_id.text, output_index.integer, address.text, amount.numeric, spent.boolean )
CREATE TABLE trading_platform.dapps ( dapp_id.text, name.text, description.text, url.text )
CREATE TABLE trading_platform.peers ( peer_id.text, ip_address.text, port.integer, last_seen.timestamp )
CREATE TABLE trading_platform.metadata ( metadata_id.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 )
##Table Structure
CREATE TABLE transportation.drivers ( driver_id.text, employee_id.text, first_name.text, last_name.text, license_number.text, license_expiry_date.date, contact_number.text, email.text, hire_date.date, status.text )

[User] For each passenger, show their passenger_id, first_name, last_name, the date and time of their earliest booking, and the date and time of their latest booking.

[Assistant]
SELECT p.passenger_id,
       p.first_name,
       p.last_name,
       MIN(b.booking_time) AS earliest_booking_time,
       MAX(b.booking_time) AS latest_booking_time
FROM transportation.passengers p
LEFT JOIN transportation.bookings b
  ON p.passenger_id = b.passenger_id
GROUP BY p.passenger_id,
         p.first_name,
         p.last_name;

[User] Show each pair of passengers who share the same loyalty_program_id but have different registration times. Return p1.first_name AS earlier, p2.first_name AS later, and loyalty_program_id.

[Assistant]
SELECT p1.first_name AS earlier, p2.first_name AS later, p1.loyalty_program_id
FROM transportation.passengers p1
JOIN transportation.passengers p2
  ON p1.loyalty_program_id = p2.loyalty_program_id
  AND p1.created_at < p2.created_at;

[User] Actually, only include pairs where the earlier registration happened before '2023-01-01'.

[Assistant]
SELECT p1.first_name AS earlier, p2.first_name AS later, p1.loyalty_program_id
FROM transportation.passengers p1
JOIN transportation.passengers p2
  ON p1.loyalty_program_id = p2.loyalty_program_id
  AND p1.created_at < p2.created_at
WHERE p1.created_at < '2023-01-01';

[User] Could you list all pairs of developers in the same country but different companies? Return developer1, developer2, and country.

[Assistant]
SELECT d1.name AS developer1,
       d2.name AS developer2,
       d1.country
FROM gaming_technology.developers d1
JOIN gaming_technology.developers d2
  ON d1.country = d2.country
 AND d1.developer_id < d2.developer_id;

[User] Now restrict pairs to only those in country 'USA' or 'Canada'.

[Assistant]
SELECT d1.name AS developer1,
       d2.name AS developer2,
       d1.country
FROM gaming_technology.developers d1
JOIN gaming_technology.developers d2
  ON d1.country = d2.country
 AND d1.developer_id < d2.developer_id
WHERE d1.country IN ('USA', 'Canada');

[User] Sort the pairs by developer1 name ascending.

[Assistant]
SELECT d1.name AS developer1,
       d2.name AS developer2,
       d1.country
FROM gaming_technology.developers d1
JOIN gaming_technology.developers d2
  ON d1.country = d2.country
 AND d1.developer_id < d2.developer_id
WHERE d1.country IN ('USA', 'Canada')
ORDER BY d1.name ASC;

[User] List all insurance products along with their type and base premium. Also, show whether each product is active.

[Assistant] SELECT product_id, product_name, product_type, base_premium, is_active FROM insurance.insurance_products;

[User] Can you filter the results to only show insurance products of type 'auto'?

[Assistant] SELECT product_id, product_name, product_type, base_premium, is_active FROM insurance.insurance_products WHERE product_type = 'auto';

[User] Also, sort these results by the base premium in ascending order.

[Assistant] SELECT product_id, product_name, product_type, base_premium, is_active FROM insurance.insurance_products WHERE product_type = 'auto' ORDER BY base_premium ASC;

[User] Show me the usernames of users who have bought or sold assets classified as 'token', along with the name and symbol of the asset they traded.

[Assistant] SELECT DISTINCT T1.username, T3.name, T3.symbol FROM users AS T1 JOIN trades AS T2 ON T1.user_id = T2.buyer_id OR T1.user_id = T2.seller_id JOIN assets AS T3 ON T2.asset_id = T3.asset_id WHERE T3.type = 'token';

[User] Instead of listing, count how many unique 'token' assets each user has traded. Show the username and the count, ordered by count descending.

[Assistant] SELECT T1.username, COUNT(DISTINCT T2.asset_id) FROM users AS T1 JOIN trades AS T2 ON T1.user_id = T2.buyer_id OR T1.user_id = T2.seller_id JOIN assets AS T3 ON T2.asset_id = T3.asset_id WHERE T3.type = 'token' GROUP BY 1 ORDER BY 2 DESC;

[User] Which drivers have licenses expiring before 2025-01-01, and what are their first and last names along with the license expiry date?

[Assistant] SELECT driver_id, first_name, last_name, license_expiry_date FROM transportation.drivers WHERE license_expiry_date < '2025-01-01';

[User] From this list, only include drivers whose status is 'Active'.

[Assistant] SELECT driver_id, first_name, last_name, license_expiry_date FROM transportation.drivers WHERE license_expiry_date < '2025-01-01' 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 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 blockchain.transactions ( transaction_id text, block_id text, sender_address text, receiver_address text, amount numeric, timestamp timestamp, signature text )
CREATE TABLE blockchain.addresses ( address_id text, public_key text, balance numeric )
CREATE TABLE blockchain.wallets ( wallet_id text, user_id text, address_id text, private_key text )
CREATE TABLE blockchain.users ( user_id text, username text, email text, password_hash text )
##Table Structure
CREATE TABLE hospitality_technology.rooms (
    room_id character varying(64) NOT NULL,  -- unique identifier for the room
    property_id character varying(64) NOT NULL, -- FK to properties table
    room_number character varying(10) NOT NULL, -- room number identifier (e.g., '101', 'Suite 2B')
    room_type_id character varying(64) NOT NULL, -- FK to room_types table
    floor integer, -- floor number the room is on
    status character varying(50) NOT NULL, -- e.g., Available, Occupied, Cleaning, OutOfOrder, Maintenance
    is_smoking boolean NOT NULL DEFAULT false, -- smoking allowed flag
    features text, -- description of features (e.g., Balcony, Sea View, Jacuzzi)
    current_condition text, -- notes on room condition
    last_cleaned_at timestamp with time zone, -- timestamp of last cleaning
    PRIMARY KEY (room_id),
    FOREIGN KEY (property_id) REFERENCES hospitality_technology.properties(property_id),
    FOREIGN KEY (room_type_id) REFERENCES hospitality_technology.room_types(room_type_id)
)
##Table Structure
CREATE TABLE legal_services.cases ( case_id text, case_number text, case_name text, client_id text, lead_lawyer_id text, case_type text, status text, date_opened timestamp, date_closed timestamp, description text, court_jurisdiction text )
##Table Structure
CREATE TABLE transportation.drivers ( driver_id text PRIMARY KEY, employee_id text, first_name text, last_name text, license_number text, license_expiry_date date, contact_number text, email text, hire_date date, status text )

[User] Show the names and emails of all guests who have communication consent enabled.

[Assistant] SELECT first_name, last_name, email FROM hospitality_technology.guests WHERE communication_consent = TRUE;

[User] Only include guests who have a loyalty member ID.

[Assistant] SELECT first_name, last_name, email FROM hospitality_technology.guests WHERE communication_consent = TRUE AND loyalty_member_id IS NOT NULL;

[User] List all address IDs with a balance under 50, along with the count of transactions they have received.

[Assistant]
SELECT a.address_id, a.balance, COUNT(t.transaction_id) AS received_count
FROM blockchain.addresses a
LEFT JOIN blockchain.transactions t ON a.address_id = t.receiver_address
WHERE a.balance < 50
GROUP BY a.address_id, a.balance;

[User] Now only include addresses that have received at least 5 transactions.

[Assistant]
SELECT a.address_id, a.balance, COUNT(t.transaction_id) AS received_count
FROM blockchain.addresses a
LEFT JOIN blockchain.transactions t ON a.address_id = t.receiver_address
WHERE a.balance < 50
GROUP BY a.address_id, a.balance
HAVING COUNT(t.transaction_id) >= 5;

[User] Also include the latest transaction timestamp for each address.

[Assistant]
SELECT a.address_id, a.balance, COUNT(t.transaction_id) AS received_count, MAX(t.timestamp) AS last_received
FROM blockchain.addresses a
LEFT JOIN blockchain.transactions t ON a.address_id = t.receiver_address
WHERE a.balance < 50
GROUP BY a.address_id, a.balance
HAVING COUNT(t.transaction_id) >= 5;

[User] How many rooms are there on each floor?

[Assistant] SELECT floor, COUNT(*) FROM hospitality_technology.rooms GROUP BY floor

[User] Only show floors with more than 10 rooms.

[Assistant] SELECT floor, COUNT(*) FROM hospitality_technology.rooms GROUP BY floor HAVING COUNT(*) > 10

[User] Show me all pairs of cases led by the same lawyer, including both case names and the lead lawyer ID.

[Assistant]
SELECT c1.lead_lawyer_id,
       c1.case_name AS case_name_1,
       c2.case_name AS case_name_2
FROM legal_services.cases c1
JOIN legal_services.cases c2
  ON c1.lead_lawyer_id = c2.lead_lawyer_id
  AND c1.case_id < c2.case_id;

[User] Actually, only include pairs where the case types are also the same.

[Assistant]
SELECT c1.lead_lawyer_id,
       c1.case_name AS case_name_1,
       c2.case_name AS case_name_2
FROM legal_services.cases c1
JOIN legal_services.cases c2
  ON c1.lead_lawyer_id = c2.lead_lawyer_id
  AND c1.case_type = c2.case_type
  AND c1.case_id < c2.case_id;

[User] Also, show me the earliest opening date between the two cases for each pair.

[Assistant]
SELECT c1.lead_lawyer_id,
       c1.case_name AS case_name_1,
       c2.case_name AS case_name_2,
       LEAST(c1.date_opened, c2.date_opened) AS earliest_open_date
FROM legal_services.cases c1
JOIN legal_services.cases c2
  ON c1.lead_lawyer_id = c2.lead_lawyer_id
  AND c1.case_type = c2.case_type
  AND c1.case_id < c2.case_id;

[User] For each driver status, find the earliest and latest hire date. Show status, earliest hire date, and latest hire date.

[Assistant]
SELECT
  status,
  MIN(hire_date) AS earliest_hire_date,
  MAX(hire_date) AS latest_hire_date
FROM transportation.drivers
GROUP BY
  status
ORDER BY
  status;

[User] The SQL seems correct, but can you also include the total number of drivers for each status?

[Assistant]
SELECT
  status,
  COUNT(*) AS driver_count,
  MIN(hire_date) AS earliest_hire_date,
  MAX(hire_date) AS latest_hire_date
FROM transportation.drivers
GROUP BY
  status
ORDER BY
  status;

[User] Now, restrict the results to only show statuses that have more than 5 drivers and where the latest hire date is after '2023-01-01'. Order the results by the total number of drivers in descending order.

[Assistant]
SELECT
  status,
  COUNT(*) AS driver_count,
  MIN(hire_date) AS earliest_hire_date,
  MAX(hire_date) AS latest_hire_date
FROM transportation.drivers
GROUP BY
  status
HAVING
  COUNT(*) > 5 AND MAX(hire_date) > '2023-01-01'
ORDER BY
  driver_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 social_media.users ( user_id character varying(64) NOT NULL, username character varying(50) NOT NULL UNIQUE, email character varying(128) NOT NULL UNIQUE, password_hash text NOT NULL, full_name character varying(100), profile_picture_url text, bio text, location character varying(100), created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, updated_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, is_verified boolean NOT NULL DEFAULT false, PRIMARY KEY (user_id) )
CREATE TABLE social_media.comments ( comment_id text PRIMARY KEY, post_id text, user_id text, parent_comment_id text, content text, created_at timestamp, updated_at timestamp )
CREATE TABLE social_media.likes ( like_id text PRIMARY KEY, user_id text, post_id text, comment_id text, created_at timestamp )
CREATE TABLE social_media.follows ( follow_id text PRIMARY KEY, follower_user_id text, following_user_id text, created_at timestamp )
CREATE TABLE social_media.hashtags ( hashtag_id.text, 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.conversations ( conversation_id character varying(64) NOT NULL, created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, last_message_at timestamp, is_group_chat boolean NOT NULL DEFAULT false, group_name character varying(100), PRIMARY KEY (conversation_id) )
CREATE TABLE social_media.conversation_participants ( participant_id text PRIMARY KEY, conversation_id text, user_id text, joined_at timestamp, last_read_at timestamp )
CREATE TABLE social_media.notifications ( notification_id text, 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 )
##Table Structure
CREATE TABLE government_services.service_locations (
    location_id character varying(64) NOT NULL, -- unique identifier for the physical location
    agency_id character varying(64) NOT NULL, -- FK to agencies table
    location_name character varying(200), -- e.g., Downtown DMV Office
    address text NOT NULL,
    city character varying(100),
    state character varying(50),
    postal_code character varying(20),
    latitude numeric(9, 6),
    longitude numeric(9, 6),
    operating_hours text, -- description of opening times
    contact_phone character varying(32),
    is_accessible boolean, -- accessibility information (e.g., wheelchair access)
    PRIMARY KEY (location_id)
)
##Table Structure
CREATE TABLE financial_services.accounts ( account_id text, customer_id text, account_number text, account_type text, balance numeric, currency text, opened_date date, status text, interest_rate numeric, last_updated_at timestamp )
##Table Structure
CREATE TABLE hospitality_technology.staff ( staff_id text PRIMARY KEY, property_id text, first_name text, last_name text, position text, work_email text, work_phone text, hire_date date, termination_date date, is_active boolean, access_level int, manager_id text, created_at timestamp )
CREATE TABLE hospitality_technology.services ( service_id character varying(64) NOT NULL, property_id character varying(64) NOT NULL, service_name character varying(150) NOT NULL, description text, category character varying(100), price numeric(10, 2) NOT NULL, unit character varying(30), is_available boolean NOT NULL DEFAULT true, department character varying(100), PRIMARY KEY (service_id), FOREIGN KEY (property_id) REFERENCES hospitality_technology.properties(property_id) )
CREATE TABLE hospitality_technology.payments ( payment_id.text, reservation_id.text, guest_id.text, bill_id.text, amount.numeric, currency_code.text, payment_method.text, card_type.text, card_last_four.text, transaction_ref.text, payment_timestamp.timestamp, status.text, staff_id_processed.text, notes.text )
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 legal_services.cases (
    case_id character varying(64) NOT NULL,  -- unique identifier for the case/matter
    case_number character varying(100) UNIQUE, -- official case number (court or internal)
    case_name text NOT NULL, -- descriptive name or title for the case
    client_id character varying(64) NOT NULL, -- FK to clients table
    lead_lawyer_id character varying(64) NOT NULL, -- FK to lawyers table (primary lawyer responsible)
    case_type character varying(100) NOT NULL, -- e.g., Litigation, Corporate, Family Law, IP
    status character varying(50) NOT NULL, -- e.g., Open, Closed, Pending, On Hold, Appealed
    date_opened timestamp NOT NULL, -- date the case was formally opened
    date_closed timestamp, -- date the case was closed (nullable)
    description text, -- detailed description of the case
    court_jurisdiction character varying(128), -- court or jurisdiction if applicable
    PRIMARY KEY (case_id)
)

[User] For hashtag ID 'H789', get each post ID and the number of distinct comments that have been made on those posts.

[Assistant]
SELECT ph.post_id,
       COUNT(DISTINCT c.comment_id) AS comment_count
FROM social_media.post_hashtags ph
JOIN social_media.comments c ON ph.post_id = c.post_id
WHERE ph.hashtag_id = 'H789'
GROUP BY ph.post_id;

[User] List the names and cities of all service locations, along with the agency ID, where the locations are marked as accessible.

[Assistant] SELECT location_name, city, agency_id FROM government_services.service_locations WHERE is_accessible = TRUE;

[User] Can you also include the state for each location and sort the results by city alphabetically?

[Assistant] SELECT location_name, city, state, agency_id FROM government_services.service_locations WHERE is_accessible = TRUE ORDER BY city ASC;

[User] Show the total and average balance for each account_type.

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

[User] Exclude any account types where the total balance is zero or negative.

[Assistant] SELECT account_type, SUM(balance) AS total_balance, AVG(balance) AS avg_balance FROM financial_services.accounts GROUP BY account_type HAVING SUM(balance) > 0;

[User] Sort the output by average balance in descending order.

[Assistant] SELECT account_type, SUM(balance) AS total_balance, AVG(balance) AS avg_balance FROM financial_services.accounts GROUP BY account_type HAVING SUM(balance) > 0 ORDER BY avg_balance DESC;

[User] List all staff members who processed payments for guest ID 'G123', including their first name, last name, and the payment ID.

[Assistant] SELECT T1.first_name, T1.last_name, T2.payment_id FROM staff AS T1 JOIN payments AS T2 ON T1.staff_id = T2.staff_id_processed WHERE T2.guest_id = 'G123';

[User] List the case ID, case number, and case name for all cases with status 'Open'.

[Assistant] SELECT case_id, case_number, case_name FROM legal_services.cases WHERE status = 'Open';

[User] Now, only show those cases opened in the year 2023.

[Assistant] SELECT case_id, case_number, case_name FROM legal_services.cases WHERE status = 'Open' AND EXTRACT(YEAR FROM date_opened) = 2023;

[User] Great, could you also show the lead lawyer ID and count how many open cases each of those lawyers has opened in 2023, displaying this count alongside the case details for each case? Order the results by date opened ascending.

[Assistant] SELECT c.case_id, c.case_number, c.case_name, c.lead_lawyer_id, lawyer_case_counts.case_count FROM legal_services.cases AS c JOIN ( SELECT lead_lawyer_id, COUNT(*) AS case_count FROM legal_services.cases WHERE status = 'Open' AND EXTRACT(YEAR FROM date_opened) = 2023 GROUP BY lead_lawyer_id ) AS lawyer_case_counts ON c.lead_lawyer_id = lawyer_case_counts.lead_lawyer_id WHERE c.status = 'Open' AND EXTRACT(YEAR FROM c.date_opened) = 2023 ORDER BY c.date_opened ASC;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement. ##Table Structure
CREATE TABLE 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 )
##Table Structure
CREATE TABLE blockchain.blocks (
    block_id character varying(64) NOT NULL,  -- unique identifier for the block
    previous_block_id character varying(64), -- identifier of the previous block
    timestamp timestamp NOT NULL, -- time when the block was mined
    nonce integer NOT NULL, -- nonce value used in the proof of work
    merkle_root character varying(128) NOT NULL, -- root of the Merkle tree for transactions
    difficulty integer NOT NULL, -- difficulty level of the block
    PRIMARY KEY (block_id)
)
##Table Structure
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.service_locations (
    location_id character varying(64) NOT NULL, -- unique identifier for the physical location
    agency_id character varying(64) NOT NULL, -- FK to agencies table
    location_name character varying(200), -- e.g., Downtown DMV Office
    address text NOT NULL,
    city character varying(100),
    state character varying(50),
    postal_code character varying(20),
    latitude numeric(9, 6),
    longitude numeric(9, 6),
    operating_hours text, -- description of opening times
    contact_phone character varying(32),
    is_accessible boolean, -- accessibility information (e.g., wheelchair access)
    PRIMARY KEY (location_id)
)
CREATE TABLE government_services.appointments ( appointment_id text, 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 )
##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.applications (
    application_id character varying(64) NOT NULL, -- unique identifier for the application
    citizen_id character varying(64) NOT NULL, -- FK to citizens table
    service_id character varying(64) NOT NULL, -- FK to services table
    submitted_at timestamp NOT NULL, -- time the application was submitted
    status character varying(50) NOT NULL, -- e.g., Submitted, Processing, Approved, Rejected, Pending Info
    last_updated_at timestamp NOT NULL, -- time the status or details last changed
    assigned_employee_id character varying(64), -- FK to employees table (optional)
    decision_date date, -- date when a final decision was made
    notes text, -- internal notes or citizen-provided comments
    reference_number character varying(100) UNIQUE, -- publicly visible reference number
    PRIMARY KEY (application_id)
)
##Table Structure
CREATE TABLE hospitality_technology.room_types (
    room_type_id character varying(64) NOT NULL, -- unique identifier for the room type
    property_id character varying(64) NOT NULL, -- FK to properties table (type might be property-specific)
    type_name character varying(100) NOT NULL, -- e.g., Standard King, Deluxe Queen, Executive Suite
    description text, -- description of the room type
    base_rate numeric(10, 2) NOT NULL, -- standard price per night
    max_occupancy integer NOT NULL, -- maximum number of guests
    bed_type character varying(50), -- e.g., King, Queen, 2 Doubles, Twin
    area_sqft numeric(8,2), -- size of the room in square feet
    amenities text, -- comma-separated list or JSON of amenities
    PRIMARY KEY (room_type_id),
    FOREIGN KEY (property_id) REFERENCES hospitality_technology.properties(property_id)
)
CREATE TABLE hospitality_technology.guests ( guest_id text PRIMARY KEY, first_name text, last_name text, email text, phone_number text, date_of_birth date, address_line1 text, city text, state_province text, postal_code text, country_code text, preferences text, loyalty_member_id text, communication_consent boolean, created_at timestamp, updated_at timestamp )

[User] Can you list all appointments along with the scheduled start time, purpose, and booking method, as well as the employee ID and location ID for each appointment?

[Assistant] SELECT appointment_id, scheduled_start_time, purpose, booking_method, employee_id, location_id FROM government_services.appointments;

[User] Now, only include appointments that are scheduled for a future date and have the status 'Scheduled'.

[Assistant] SELECT appointment_id, scheduled_start_time, purpose, booking_method, employee_id, location_id FROM government_services.appointments WHERE scheduled_start_time > CURRENT_TIMESTAMP AND status = 'Scheduled';

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

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

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

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

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

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

[User] List all appointments along with their scheduled start time and the purpose, as well as the name of the location where each appointment is scheduled.

[Assistant]
SELECT a.appointment_id, a.scheduled_start_time, a.purpose, l.location_name
FROM government_services.appointments a
JOIN government_services.service_locations l ON a.location_id = l.location_id;

[User] List the number of applications submitted by each citizen.

[Assistant]
SELECT c.citizen_id, c.first_name, c.last_name, COUNT(a.application_id) AS application_count
FROM government_services.citizens c
LEFT JOIN government_services.applications a ON c.citizen_id = a.citizen_id
GROUP BY c.citizen_id, c.first_name, c.last_name;

[User] Retrieve all room types with a base_rate above 150 for each property.

[Assistant]
SELECT property_id, type_name, base_rate
FROM hospitality_technology.room_types
WHERE base_rate > 150;

[User] Also filter to only include room types with max_occupancy >= 3.

[Assistant]
SELECT property_id, type_name, base_rate
FROM hospitality_technology.room_types
WHERE base_rate > 150
  AND max_occupancy >= 3;

[User] Finally, show guest first and last names of guests created after '2023-01-01' who could book these room types.

[Assistant]
SELECT g.first_name, g.last_name, rt.property_id, rt.type_name, rt.base_rate
FROM hospitality_technology.room_types rt
CROSS JOIN hospitality_technology.guests g
WHERE rt.base_rate > 150
  AND rt.max_occupancy >= 3
  AND g.created_at > '2023-01-01';


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement. ##Table Structure
CREATE TABLE 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)
)
##Table Structure
CREATE TABLE web3.events ( event_id character varying(64) NOT NULL, contract_id character varying(64) NOT NULL, event_name character varying(128) NOT NULL, data text NOT NULL, emitted_at timestamp NOT NULL, transaction_id character varying(64) NOT NULL, log_index integer NOT NULL, PRIMARY KEY (event_id) )
##Table Structure
CREATE TABLE legal_services.time_entries ( entry_id text, case_id text, lawyer_id text, date_worked date, hours_spent numeric, billing_rate numeric, description text, is_billable boolean, is_billed boolean, invoice_id text, created_at timestamp )
CREATE TABLE legal_services.invoices ( invoice_id text, invoice_number text, client_id text, case_id text, issue_date date, due_date date, total_amount numeric, amount_paid numeric, status text, payment_date timestamp, notes text, created_at timestamp )
CREATE TABLE legal_services.appointments ( appointment_id text, client_id text, lawyer_id text, case_id text, start_time timestamp, end_time timestamp, location text, subject text, notes text, status text, created_at timestamp )
##Table Structure
CREATE TABLE social_media.comments ( comment_id text PRIMARY KEY, post_id text, user_id text, parent_comment_id text, content text, created_at timestamp, updated_at timestamp )
CREATE TABLE social_media.conversations ( conversation_id character varying(64) NOT NULL, created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, last_message_at timestamp, is_group_chat boolean NOT NULL DEFAULT false, group_name character varying(100), PRIMARY KEY (conversation_id) )
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 )
##Table Structure
CREATE TABLE healthcare.patients ( patient_id character varying(64) NOT NULL, first_name character varying(100) NOT NULL, last_name character varying(100) NOT NULL, date_of_birth date NOT NULL, gender character varying(10), address text, phone_number character varying(20), email character varying(128) UNIQUE, emergency_contact_name character varying(200), emergency_contact_phone character varying(20), created_at timestamp with time zone NOT NULL DEFAULT current_timestamp, updated_at timestamp with time zone NOT NULL DEFAULT current_timestamp, PRIMARY KEY (patient_id) )
CREATE TABLE healthcare.medical_records ( record_id character varying(64) NOT NULL, patient_id character varying(64) NOT NULL, appointment_id character varying(64) UNIQUE, doctor_id character varying(64) NOT NULL, record_date timestamp with time zone NOT NULL, chief_complaint text, present_illness_history text, past_medical_history text, physical_examination_notes text, assessment text, treatment_plan text, vitals jsonb, created_at timestamp with time zone NOT NULL DEFAULT current_timestamp, PRIMARY KEY (record_id) )
CREATE TABLE healthcare.diagnoses ( diagnosis_id text PRIMARY KEY, record_id text, patient_id text, doctor_id text, diagnosis_code text, code_type text, description text, diagnosis_date date, status text, is_chronic boolean )
CREATE TABLE healthcare.prescriptions ( prescription_id.text, record_id.text, patient_id.text, doctor_id.text, medication_id.text, dosage.text, frequency.text, route.text, start_date.date, end_date.date, quantity_dispensed.numeric, refills_allowed.integer, prescription_date.timestamp )
CREATE TABLE healthcare.insurance_plans ( plan_id.text, plan_name.text, insurance_provider.text, plan_type.text, contact_phone.text, website.text )
##Table Structure
CREATE TABLE hospitality_technology.rooms (
    room_id character varying(64) NOT NULL,  -- unique identifier for the room
    property_id character varying(64) NOT NULL, -- FK to properties table
    room_number character varying(10) NOT NULL, -- room number identifier (e.g., '101', 'Suite 2B')
    room_type_id character varying(64) NOT NULL, -- FK to room_types table
    floor integer, -- floor number the room is on
    status character varying(50) NOT NULL, -- e.g., Available, Occupied, Cleaning, OutOfOrder, Maintenance
    is_smoking boolean NOT NULL DEFAULT false, -- smoking allowed flag
    features text, -- description of features (e.g., Balcony, Sea View, Jacuzzi)
    current_condition text, -- notes on room condition
    last_cleaned_at timestamp with time zone, -- timestamp of last cleaning
    PRIMARY KEY (room_id),
    FOREIGN KEY (property_id) REFERENCES hospitality_technology.properties(property_id),
    FOREIGN KEY (room_type_id) REFERENCES hospitality_technology.room_types(room_type_id)
)

[User] Find all pairs of citizens who share the same first name and gender but have different last names. Display the shared first name, gender, the full name of the first citizen in the pair, and the full name of the second citizen.

[Assistant] SELECT c1.first_name, c1.gender, c1.first_name || ' ' || c1.last_name AS citizen1_full_name, c2.first_name || ' ' || c2.last_name AS citizen2_full_name FROM government_services.citizens AS c1 JOIN government_services.citizens AS c2 ON c1.first_name = c2.first_name AND c1.gender = c2.gender AND c1.last_name <> c2.last_name AND c1.citizen_id < c2.citizen_id;

[User] Show the event_id, transaction_id, and emitted_at timestamp for all events with event_name 'Approval' and contract_id '0xdeadbeefdeadbeefdeadbeefdeadbeefdeadbeef'.

[Assistant] SELECT event_id, transaction_id, emitted_at FROM web3.events WHERE event_name = 'Approval' AND contract_id = '0xdeadbeefdeadbeefdeadbeefdeadbeefdeadbeef';

[User] List all invoices with a total_amount less than 1000 and show the associated client's ID and case ID.

[Assistant]
SELECT invoice_id, client_id, case_id, total_amount
FROM legal_services.invoices
WHERE total_amount < 1000;

[User] Actually, can you also include the invoice status and order the results by total_amount ascending?

[Assistant]
SELECT invoice_id, client_id, case_id, total_amount, status
FROM legal_services.invoices
WHERE total_amount < 1000
ORDER BY total_amount ASC;

[User] Now, only show invoices where the status is 'Sent' or 'Overdue', and include the issue_date as well.

[Assistant]
SELECT invoice_id, client_id, case_id, total_amount, status, issue_date
FROM legal_services.invoices
WHERE total_amount < 1000 AND status IN ('Sent', 'Overdue')
ORDER BY total_amount ASC;

[User] How many comments were created in the month of March 2024?

[Assistant] SELECT COUNT(*) FROM social_media.comments WHERE created_at >= '2024-03-01' AND created_at < '2024-04-01';

[User] How many prescriptions have been issued for each medication?

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

[User] Exclude null or empty medication_ids and only show medications with more than 5 prescriptions.

[Assistant] SELECT medication_id, COUNT(*) AS prescription_count FROM healthcare.prescriptions WHERE medication_id IS NOT NULL AND medication_id <> '' GROUP BY medication_id HAVING COUNT(*) > 5;

[User] List all rooms that have not been cleaned in the last 7 days, showing their room number, property ID, and last cleaned date.

[Assistant] SELECT room_number, property_id, last_cleaned_at FROM hospitality_technology.rooms WHERE last_cleaned_at < NOW() - INTERVAL '7 days';

[User] Now, only include those rooms with status 'Occupied' or 'Cleaning', and sort the results by last cleaned date descending.

[Assistant] SELECT room_number, property_id, last_cleaned_at FROM hospitality_technology.rooms WHERE last_cleaned_at < NOW() - INTERVAL '7 days' AND status IN ('Occupied', 'Cleaning') ORDER BY last_cleaned_at DESC;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement. ##Table Structure
CREATE TABLE insurance.agents ( agent_id text, first_name text, last_name text, agency_name text, license_number text, license_state text, contact_email text, contact_phone text, hire_date date, termination_date date, status text, commission_rate numeric, manager_id text )
CREATE TABLE insurance.premium_payments (
    payment_id character varying(64) NOT NULL, -- unique identifier for the payment
    policy_id character varying(64) NOT NULL, -- identifier of the policy the payment is for (FK to policies)
    customer_id character varying(64) NOT NULL, -- identifier of the customer making the payment (FK to customers)
    payment_date timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, -- date the payment was received
    amount_paid numeric(12, 2) NOT NULL, -- amount of the payment
    payment_method character varying(50), -- e.g., Credit Card, Bank Transfer, Check
    transaction_reference character varying(128) UNIQUE, -- reference from payment processor
    due_date date, -- due date for this payment installment
    payment_period_start date, -- start date of the period this payment covers
    payment_period_end date, -- end date of the period this payment covers
    status character varying(30) NOT NULL DEFAULT 'Completed', -- e.g., Completed, Pending, Failed, Refunded
    PRIMARY KEY (payment_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 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 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.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 healthcare.patients ( patient_id character varying(64) NOT NULL, first_name character varying(100) NOT NULL, last_name character varying(100) NOT NULL, date_of_birth date NOT NULL, gender character varying(10), address text, phone_number character varying(20), email character varying(128) UNIQUE, emergency_contact_name character varying(200), emergency_contact_phone character varying(20), created_at timestamp with time zone NOT NULL DEFAULT current_timestamp, updated_at timestamp with time zone NOT NULL DEFAULT current_timestamp, PRIMARY KEY (patient_id) )
CREATE TABLE healthcare.doctors ( doctor_id character varying(64) NOT NULL, first_name character varying(100) NOT NULL, last_name character varying(100) NOT NULL, specialty character varying(100) NOT NULL, license_number character varying(50) UNIQUE NOT NULL, phone_number character varying(20), email character varying(128) UNIQUE, hospital_affiliation_id character varying(64), created_at timestamp with time zone NOT NULL DEFAULT current_timestamp, updated_at timestamp with time zone NOT NULL DEFAULT current_timestamp, PRIMARY KEY (doctor_id) )
CREATE TABLE healthcare.diagnoses ( diagnosis_id character varying(64) NOT NULL, record_id character varying(64) NOT NULL, patient_id character varying(64) NOT NULL, doctor_id character varying(64) NOT NULL, diagnosis_code character varying(20) NOT NULL, code_type character varying(10) NOT NULL DEFAULT 'ICD-10', description text, diagnosis_date date NOT NULL, status character varying(32) NOT NULL, is_chronic boolean DEFAULT false, PRIMARY KEY (diagnosis_id) )
CREATE TABLE healthcare.medications ( medication_id character varying(64) NOT NULL, medication_name character varying(255) NOT NULL, generic_name character varying(255), manufacturer character varying(100), ndc_code character varying(20) UNIQUE, description text, PRIMARY KEY (medication_id) )
CREATE TABLE healthcare.insurance_plans ( plan_id character varying(64) NOT NULL, plan_name character varying(200) NOT NULL, insurance_provider character varying(100) NOT NULL, plan_type character varying(50), contact_phone character varying(20), website character varying(255), PRIMARY KEY (plan_id) )
CREATE TABLE healthcare.patient_insurance ( patient_insurance_id character varying(64) NOT NULL, patient_id character varying(64) NOT NULL, plan_id character varying(64) NOT NULL, policy_number character varying(100) NOT NULL, group_number character varying(100), subscriber_name character varying(200), effective_date date NOT NULL, expiration_date date, is_primary boolean NOT NULL DEFAULT true, PRIMARY KEY (patient_insurance_id), UNIQUE (patient_id, plan_id, policy_number) )

[User] Can you retrieve the document_id, file_name, file_size_bytes, uploaded_at, and the full name of the agent (first and last name concatenated) for all documents uploaded in 2024 by active agents licensed in CA?

[Assistant] SELECT cd.document_id, cd.file_name, cd.file_size_bytes, cd.uploaded_at, a.first_name || ' ' || a.last_name AS agent_full_name FROM insurance.claim_documents cd JOIN insurance.agents a ON cd.uploaded_by = a.agent_id WHERE a.license_state = 'CA' AND a.status = 'Active' AND cd.uploaded_at BETWEEN '2024-01-01' AND '2024-12-31';

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

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

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

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

[User] List each user along with how many image-type posts they've made, showing user_id and image_post_count, sorted by the count descending.

[Assistant]
SELECT user_id, COUNT(*) AS image_post_count
FROM social_media.posts
WHERE media_type = 'image'
GROUP BY user_id
ORDER BY image_post_count DESC;

[User] List all insurance plan names and their associated insurance provider.

[Assistant] SELECT plan_name, insurance_provider FROM healthcare.insurance_plans;

[User] Only show plans where the insurance provider name contains the word 'Health'.

[Assistant]
SELECT plan_name, insurance_provider FROM healthcare.insurance_plans
WHERE insurance_provider ILIKE '%Health%';