[User] For each guest, list reservation_id, guest_id, check_in_date, and the next reservation_id and its check_in_date.

[Assistant]
SELECT r1.reservation_id,
       r1.guest_id,
       r1.check_in_date,
       r2.reservation_id AS next_reservation_id,
       r2.check_in_date   AS next_check_in_date
FROM reservations r1
LEFT JOIN reservations r2
  ON r1.guest_id = r2.guest_id
 AND r2.check_in_date = (
       SELECT MIN(check_in_date)
       FROM reservations
       WHERE guest_id = r1.guest_id
         AND check_in_date > r1.check_in_date
     );

[User] Only include guests who have at least two reservations.

[Assistant]
SELECT r1.reservation_id,
       r1.guest_id,
       r1.check_in_date,
       r2.reservation_id AS next_reservation_id,
       r2.check_in_date   AS next_check_in_date
FROM reservations r1
LEFT JOIN reservations r2
  ON r1.guest_id = r2.guest_id
 AND r2.check_in_date = (
       SELECT MIN(check_in_date)
       FROM reservations
       WHERE guest_id = r1.guest_id
         AND check_in_date > r1.check_in_date
     )
WHERE r1.guest_id IN (
  SELECT guest_id
  FROM reservations
  GROUP BY guest_id
  HAVING COUNT(*) >= 2
);

[User] Also, only show next reservations that occur within 30 days of the current reservation.

[Assistant]
SELECT r1.reservation_id,
       r1.guest_id,
       r1.check_in_date,
       r2.reservation_id AS next_reservation_id,
       r2.check_in_date   AS next_check_in_date
FROM reservations r1
LEFT JOIN reservations r2
  ON r1.guest_id = r2.guest_id
 AND r2.check_in_date = (
       SELECT MIN(check_in_date)
       FROM reservations
       WHERE guest_id = r1.guest_id
         AND check_in_date > r1.check_in_date
     )
   AND r2.check_in_date <= r1.check_in_date + INTERVAL '30 days'
WHERE r1.guest_id IN (
  SELECT guest_id
  FROM reservations
  GROUP BY guest_id
  HAVING COUNT(*) >= 2
);


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE 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 )

[User] Which clients have appointments scheduled for a case that also has at least one invoice issued? Please show the client_id, appointment_id, appointment start_time, related case_id, and invoice_number.

[Assistant]
SELECT a.client_id, a.appointment_id, a.start_time, a.case_id, i.invoice_number
FROM legal_services.appointments a
JOIN legal_services.invoices i ON a.case_id = i.case_id
WHERE a.status = 'Scheduled';


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 token_metas ( block_timestamp timestamp, block_number bigint, transaction_hash varchar, transaction_index bigint, from_address varchar, contract_address varchar, symbol varchar, total_supply varchar, name varchar, decimals bigint, is_erc20 integer, is_erc721 integer, is_erc1155 integer, is_proxy integer, extra_info varchar, pk integer )
CREATE TABLE erc1155_approval_for_all ( block_number bigint, block_timestamp timestamp, transaction_index integer, transaction_hash varchar, log_index integer, contract_address varchar )
CREATE TABLE erc20_balances_historical ( block_number bigint, contract_address varchar, wallet_address varchar, amount varchar, pk integer )
CREATE TABLE nft_holder_historical ( block_number bigint, contract_address varchar, wallet_address varchar, token_id varchar, contract_type varchar, amount varchar, pk integer )
CREATE TABLE sui_nfts ( object_id varchar, status varchar, collection_type varchar, package_id varchar, previous_transaction varchar, display varchar, owner varchar, name varchar )
CREATE TABLE nft_metadata ( blockchain varchar, contract_address varchar, token_id varchar, contract_name varchar, erc_type varchar, amount bigint, minter varchar, owner varchar, mint_block_number bigint, mint_time bigint, mint_transaction_hash varchar, mint_price varchar, token_uri varchar, metadata varchar, name varchar, image_uri varchar, traits varchar, updated_at bigint, status varchar, rarity_score real, rarity_rank integer, unique_attribute_count integer, pk integer )
CREATE TABLE nft_collections ( blockchain varchar, contract_address varchar, name varchar, symbol varchar, deploy_block_number bigint, deploy_block_time bigint, erc_type varchar, owner varchar, traits varchar, description varchar, slug varchar, media_info varchar, image_url varchar, banner_image_url varchar, updated_at bigint, banner varchar, token_count bigint, floor_price varchar, floor_price_symbol varchar, floor_price_contract varchar, pk integer )
CREATE TABLE token_prices ( uuid varchar, blockchain varchar, address varchar, decimals bigint, symbol varchar, price real, timestamp timestamp )
CREATE TABLE token_prices_latest ( blockchain varchar, address varchar, decimals bigint, symbol varchar, price real, timestamp timestamp )
CREATE TABLE token_info ( block_timestamp timestamp, block_number bigint, tx_index integer, tx_hash varchar, tick varchar, max_supply decimal, lim decimal, wlim decimal, dec integer, creator varchar )
CREATE TABLE mud_holesky_redstone ( address varchar, table_id varchar, key_bytes varchar, key0 varchar, key1 varchar, static_data varchar, encoded_lengths varchar, dynamic_data varchar, is_deleted boolean, block_number bigint, log_index bigint )
CREATE TABLE token_activities_avalanche ( block_timestamp timestamp, block_number bigint, tx_index integer, tx_hash varchar, log_index integer, type varchar, tick varchar, id varchar, amt decimal, from_address varchar, to_address varchar )
CREATE TABLE token_balances_avalanche ( block_number bigint, block_timestamp timestamp, tick varchar, wallet_address varchar, total_supply decimal, amount decimal )
CREATE TABLE token_info_avalanche ( block_timestamp timestamp, block_number bigint, tx_index integer, tx_hash varchar, tick varchar, max_supply decimal, lim decimal, wlim decimal, dec integer, creator varchar, minted decimal, holders decimal, txs decimal, updated_timestamp timestamp, completed_timestamp timestamp, id varchar )

[User] Show me the top 5 NFT collections with the highest token count, along with their names, symbols, and floor prices, but only include collections with a floor price greater than 0.5 ETH.

[Assistant] SELECT nc.name, nc.symbol, nc.floor_price, nc.token_count FROM nft_collections nc WHERE nc.floor_price > '0.5' AND nc.erc_type = 'ERC721' ORDER BY nc.token_count DESC LIMIT 5;

[User] Can you also include the banner image URL for these collections and filter out collections with less than 1000 tokens?

[Assistant] SELECT nc.name, nc.symbol, nc.floor_price, nc.token_count, nc.banner_image_url FROM nft_collections nc WHERE nc.floor_price > '0.5' AND nc.erc_type = 'ERC721' AND nc.token_count >= 1000 ORDER BY nc.token_count DESC LIMIT 5;

[User] Now join this with the nft_metadata table to include the average rarity score for each collection.

[Assistant] SELECT nc.name, nc.symbol, nc.floor_price, nc.token_count, nc.banner_image_url, AVG(nm.rarity_score) as avg_rarity_score FROM nft_collections nc JOIN nft_metadata nm ON nc.contract_address = nm.contract_address WHERE nc.floor_price > '0.5' AND nc.erc_type = 'ERC721' AND nc.token_count >= 1000 GROUP BY nc.name, nc.symbol, nc.floor_price, nc.token_count, nc.banner_image_url ORDER BY nc.token_count DESC LIMIT 5;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE 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 )

[User] Show each order with its previous order timestamp for the same user.

[Assistant]
SELECT o.order_id, o.user_id, o.created_at AS current_time, MAX(prev.created_at) AS previous_time
FROM trading_platform.orders o
LEFT JOIN trading_platform.orders prev
  ON o.user_id = prev.user_id
  AND prev.created_at < o.created_at
GROUP BY o.order_id, o.user_id, o.created_at
ORDER BY o.user_id, o.created_at;

[User] Filter to include only those orders where the gap between current_time and previous_time exceeds one day.

[Assistant]
SELECT *
FROM (
  SELECT o.order_id,
         o.user_id,
         o.created_at AS current_time,
         MAX(prev.created_at) AS previous_time
  FROM trading_platform.orders o
  LEFT JOIN trading_platform.orders prev
    ON o.user_id = prev.user_id
    AND prev.created_at < o.created_at
  GROUP BY o.order_id, o.user_id, o.created_at
) t
WHERE t.current_time - t.previous_time > INTERVAL '1 day'
ORDER BY t.user_id, t.current_time;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE hospitality_technology.properties (
    property_id character varying(64) NOT NULL,  -- unique identifier for the property (hotel, resort, etc.)
    property_name character varying(255) NOT NULL, -- name of the property
    address_line1 character varying(255) NOT NULL, -- primary address line
    address_line2 character varying(255), -- secondary address line
    city character varying(100) NOT NULL, -- city
    state_province character varying(100), -- state or province
    postal_code character varying(20) NOT NULL, -- zip or postal code
    country_code character varying(3) NOT NULL, -- ISO country code (e.g., USA, CAN)
    phone_number character varying(30), -- main contact phone
    email_address character varying(255), -- main contact email
    property_type character varying(50) NOT NULL, -- e.g., Hotel, Resort, B&B, Motel
    star_rating numeric(2,1), -- star rating (e.g., 4.5)
    timezone character varying(64) NOT NULL, -- IANA timezone ID (e.g., America/New_York)
    manager_staff_id character varying(64), -- FK to staff table for the general manager
    created_at timestamp with time zone NOT NULL DEFAULT current_timestamp, -- record creation time
    updated_at timestamp with time zone NOT NULL DEFAULT current_timestamp, -- record last update time
    PRIMARY KEY (property_id)
)
CREATE TABLE hospitality_technology.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 character varying(64) NOT NULL, first_name character varying(100) NOT NULL, last_name character varying(100) NOT NULL, email character varying(255) UNIQUE, phone_number character varying(30), date_of_birth date, address_line1 character varying(255), city character varying(100), state_province character varying(100), postal_code character varying(20), country_code character varying(3), preferences text, loyalty_member_id character varying(64) UNIQUE, communication_consent boolean DEFAULT true, created_at timestamp with time zone NOT NULL DEFAULT current_timestamp, updated_at timestamp with time zone NOT NULL DEFAULT current_timestamp, PRIMARY KEY (guest_id) )
CREATE TABLE hospitality_technology.reservations ( reservation_id text, property_id text, guest_id text, room_id text, room_type_id text, check_in_date date, check_out_date date, actual_check_in_ts timestamp, actual_check_out_ts timestamp, num_adults integer, num_children integer, status text, booking_source text, rate_plan_id text, total_amount numeric, amount_paid numeric, special_requests text, created_at timestamp, updated_at timestamp )
CREATE TABLE hospitality_technology.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.service_orders ( order_id text, reservation_id text, guest_id text, service_id text, staff_id_ordered text, staff_id_delivered text, order_timestamp timestamp, delivery_timestamp timestamp, quantity integer, unit_price numeric, total_price numeric, status text, notes text, bill_id text )
CREATE TABLE hospitality_technology.payments (
    payment_id character varying(64) NOT NULL,  -- unique identifier for the payment transaction
    reservation_id character varying(64), -- FK to reservations (if payment is for a stay)
    guest_id character varying(64) NOT NULL, -- FK to guests (who paid)
    bill_id character varying(64), -- FK to bills/invoices this payment applies to
    amount numeric(12,2) NOT NULL, -- amount of the payment
    currency_code character varying(3) NOT NULL, -- ISO currency code (e.g., USD, EUR)
    payment_method character varying(50) NOT NULL, -- e.g., CreditCard, Cash, BankTransfer, Points, Voucher
    card_type character varying(50), -- e.g., Visa, MasterCard, Amex (if CC)
    card_last_four character varying(4), -- last 4 digits of CC (if CC)
    transaction_ref character varying(128), -- reference ID from payment gateway or processor
    payment_timestamp timestamp with time zone NOT NULL DEFAULT current_timestamp, -- when the payment occurred
    status character varying(50) NOT NULL, -- e.g., Pending, Succeeded, Failed, Refunded, Disputed
    staff_id_processed character varying(64), -- FK to staff (who processed the payment)
    notes text, -- notes about the payment
    PRIMARY KEY (payment_id),
    FOREIGN KEY (reservation_id) REFERENCES hospitality_technology.reservations(reservation_id),
    FOREIGN KEY (guest_id) REFERENCES hospitality_technology.guests(guest_id),
    FOREIGN KEY (staff_id_processed) REFERENCES hospitality_technology.staff(staff_id)
)

[User] Get the property name, room type name, base rate, and star rating for all room types with a base_rate above 200 in properties located in the USA, sorted by base_rate in descending order.

[Assistant]
SELECT p.property_name, rt.type_name, rt.base_rate, p.star_rating
FROM hospitality_technology.room_types rt
JOIN hospitality_technology.properties p ON rt.property_id = p.property_id
WHERE rt.base_rate > 200
  AND p.country_code = 'USA'
ORDER BY rt.base_rate DESC;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE government_services.citizens ( citizen_id text PRIMARY KEY, national_id_number text, first_name text, last_name text, date_of_birth date, gender text, primary_address text, contact_email text, contact_phone text, registration_date timestamp, is_verified boolean )
CREATE TABLE government_services.agencies ( agency_id text PRIMARY KEY, agency_name text, jurisdiction_level text, primary_contact_email text, main_phone_number text, website_url text, established_date date, parent_agency_id text )
CREATE TABLE government_services.services ( service_id text PRIMARY KEY, agency_id text, service_name text, description text, category text, eligibility_criteria text, standard_fee numeric, average_processing_time_days int, is_active boolean, online_application_url text )
CREATE TABLE government_services.employees ( employee_id text PRIMARY KEY, agency_id text, first_name text, last_name text, job_title text, department text, work_email text, work_phone text, hire_date date, termination_date date, access_level text, manager_employee_id text )
CREATE TABLE government_services.service_locations ( location_id text PRIMARY KEY, agency_id text, location_name text, address text, city text, state text, postal_code text, latitude numeric, longitude numeric, operating_hours text, contact_phone text, is_accessible boolean )
CREATE TABLE government_services.appointments ( appointment_id text PRIMARY KEY, citizen_id text, employee_id text, location_id text, service_id text, scheduled_start_time timestamp, scheduled_end_time timestamp, purpose text, status text, booking_method text, created_at timestamp, notes text )
CREATE TABLE government_services.notifications ( notification_id text PRIMARY KEY, citizen_id text, application_id text, message_subject text, message_body text, channel text, sent_at timestamp, status text, related_entity_type text, related_entity_id text )

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

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


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE legal_services.clients ( client_id text, first_name text, last_name text, company_name text, email text, phone text, address text, date_registered timestamp, status text )
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 )
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 )
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 )

[User] I need a list of each case_number and case_name with the total hours spent on each case based on time_entries, but only include cases where the total hours is greater than 10.

[Assistant]
SELECT c.case_number, c.case_name, SUM(te.hours_spent) AS total_hours
FROM legal_services.cases c
JOIN legal_services.time_entries te ON c.case_id = te.case_id
GROUP BY c.case_number, c.case_name
HAVING SUM(te.hours_spent) > 10;

[User] Actually, tally only hours where is_billable is true.

[Assistant]
SELECT c.case_number, c.case_name, SUM(te.hours_spent) AS total_hours
FROM legal_services.cases c
JOIN legal_services.time_entries te ON c.case_id = te.case_id
WHERE te.is_billable = TRUE
GROUP BY c.case_number, c.case_name
HAVING SUM(te.hours_spent) > 10;

[User] Also include the client's first_name and last_name for each case.

[Assistant]
SELECT c.case_number, c.case_name, cl.first_name, cl.last_name, SUM(te.hours_spent) AS total_hours
FROM legal_services.cases c
JOIN legal_services.clients cl ON c.client_id = cl.client_id
JOIN legal_services.time_entries te ON c.case_id = te.case_id
WHERE te.is_billable = TRUE
GROUP BY c.case_number, c.case_name, cl.first_name, cl.last_name
HAVING SUM(te.hours_spent) > 10;


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

[User] Show me all participants who joined any conversation before January 1st, 2024. Return participant_id, user_id, conversation_id and the joined_at timestamp.

[Assistant] SELECT participant_id, user_id, conversation_id, joined_at FROM social_media.conversation_participants WHERE joined_at < '2024-01-01';


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE government_services.notifications ( notification_id text PRIMARY KEY, citizen_id text, application_id text, message_subject text, message_body text, channel text, sent_at timestamp, status text, related_entity_type text, related_entity_id text )

[User] For each notification, list its notification_id, message_subject, and the message_subject of the notification it relates to (assuming related_entity_type = 'notification').

[Assistant]
SELECT n.notification_id,
       n.message_subject,
       parent.message_subject AS related_message_subject
FROM government_services.notifications n
LEFT JOIN government_services.notifications parent
  ON n.related_entity_type = 'notification'
 AND n.related_entity_id = parent.notification_id;

[User] Only include notifications with status = 'Sent'.

[Assistant]
SELECT n.notification_id,
       n.message_subject,
       parent.message_subject AS related_message_subject
FROM government_services.notifications n
LEFT JOIN government_services.notifications parent
  ON n.related_entity_type = 'notification'
 AND n.related_entity_id = parent.notification_id
WHERE n.status = 'Sent';


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.comments (
    comment_id character varying(64) NOT NULL, -- unique identifier for the comment
    post_id character varying(64) NOT NULL, -- identifier of the post being commented on (FK to posts.post_id)
    user_id character varying(64) NOT NULL, -- identifier of the user who made the comment (FK to users.user_id)
    parent_comment_id character varying(64), -- identifier of the parent comment if it's a reply (FK to comments.comment_id)
    content text NOT NULL, -- textual content of the comment
    created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, -- timestamp of comment creation
    updated_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, -- timestamp of last comment edit
    PRIMARY KEY (comment_id)
)
CREATE TABLE social_media.likes ( like_id text, user_id text, post_id text, comment_id text, created_at timestamp )
CREATE TABLE social_media.hashtags ( hashtag_id character varying(64) NOT NULL, tag_name character varying(100) NOT NULL UNIQUE, created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, PRIMARY KEY (hashtag_id) )
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 text PRIMARY KEY, created_at timestamp, last_message_at timestamp, is_group_chat bool, group_name text )
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.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 )

[User] List all conversation IDs with the total number of messages sent in each conversation.

[Assistant]
SELECT conversation_id, COUNT(*) AS message_count
FROM social_media.messages
GROUP BY conversation_id;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE 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, -- unique identifier for the service
    agency_id character varying(64) NOT NULL, -- FK to agencies table
    service_name character varying(255) NOT NULL, -- name of the service (e.g., Driver's License Renewal)
    description text,
    category character varying(100), -- e.g., Licensing, Benefits, Taxation, Permits
    eligibility_criteria text, -- description of who is eligible
    standard_fee numeric(10, 2) DEFAULT 0.00, -- typical fee for the service
    average_processing_time_days integer, -- estimated processing time
    is_active boolean DEFAULT true, -- whether the service is currently offered
    online_application_url character varying(255),
    PRIMARY KEY (service_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)
)
CREATE TABLE government_services.documents ( document_id text PRIMARY KEY, 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.employees (
    employee_id character varying(64) NOT NULL, -- unique identifier for the government employee
    agency_id character varying(64) NOT NULL, -- FK to agencies table
    first_name character varying(100) NOT NULL,
    last_name character varying(100) NOT NULL,
    job_title character varying(150) NOT NULL,
    department character varying(100),
    work_email character varying(128) NOT NULL UNIQUE,
    work_phone character varying(32),
    hire_date date NOT NULL,
    termination_date date, -- null if currently employed
    access_level character varying(50), -- Role or permission level
    manager_employee_id character varying(64), -- FK to self for reporting structure
    PRIMARY KEY (employee_id)
)
CREATE TABLE government_services.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) )

[User] List the first and last names of employees and the number of services offered by their agency.

[Assistant]
SELECT e.first_name, e.last_name, COUNT(s.service_id) AS service_count
FROM government_services.employees e
LEFT JOIN government_services.services s ON e.agency_id = s.agency_id
GROUP BY e.employee_id, e.first_name, e.last_name;

[User] Include only employees whose agency offers more than 3 services.

[Assistant]
SELECT e.first_name, e.last_name, COUNT(s.service_id) AS service_count
FROM government_services.employees e
LEFT JOIN government_services.services s ON e.agency_id = s.agency_id
GROUP BY e.employee_id, e.first_name, e.last_name
HAVING COUNT(s.service_id) > 3;

[User] Add the agency name to the result.

[Assistant]
SELECT e.first_name, e.last_name, ag.agency_name, COUNT(s.service_id) AS service_count
FROM government_services.employees e
JOIN government_services.agencies ag ON e.agency_id = ag.agency_id
LEFT JOIN government_services.services s ON e.agency_id = s.agency_id
GROUP BY e.employee_id, e.first_name, e.last_name, ag.agency_name
HAVING COUNT(s.service_id) > 3;

[User] Now, only show services that are currently active in the count.

[Assistant]
SELECT e.first_name, e.last_name, ag.agency_name, COUNT(s.service_id) AS active_service_count
FROM government_services.employees e
JOIN government_services.agencies ag ON e.agency_id = ag.agency_id
LEFT JOIN government_services.services s ON e.agency_id = s.agency_id AND s.is_active = TRUE
GROUP BY e.employee_id, e.first_name, e.last_name, ag.agency_name
HAVING COUNT(s.service_id) > 3;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE token_basic_info ( coin_id.text, token_name.text, token_symbol.text, token_address.text, chain.text, price.numeric, price_change_percentage_1h.numeric, price_change_percentage_24h.numeric, price_change_percentage_7d.numeric, highest_price_24h.numeric, lowest_price_24h.numeric, market_cap.numeric, market_cap_rank.numeric, market_cap_change_percentage_24h.text, total_volume.text, narrative.text, trend_rank.numeric )
CREATE TABLE token_dexpool_info ( pair_address.text, token_name.text, token_symbol.text, chain.text, price.numeric, price_change_percentage_1h.numeric, price_change_percentage_6h.numeric, price_change_percentage_24h.numeric, makers_24h.numeric, volume_24h.numeric, liquidity.numeric, market_cap.numeric, trend_rank.numeric )
CREATE TABLE cex_token_balance ( snapshot_time.text, chain.text, address.text, exchange.text, token_address.text, token_symbol.text, balance.numeric, usd_value.numeric, price.numeric )
CREATE TABLE smart_money_token_performance ( token_address.text, token_symbol.text, pnl.numeric, net_flow.numeric, avg_cost.numeric, price.numeric, realized_ratio.numeric, roi.numeric, chain.text )

[User] Show me tokens with a 24-hour trading volume over $1,000,000 from DEX pools that also have a positive net flow from smart money addresses. Display the token symbol, chain, 24h volume, and net flow.

[Assistant] SELECT tdi.token_symbol, tdi.chain, tdi.volume_24h, smtp.net_flow FROM token_dexpool_info AS tdi JOIN smart_money_token_performance AS smtp ON tdi.token_symbol = smtp.token_symbol AND tdi.chain = smtp.chain WHERE tdi.volume_24h > 1000000 AND smtp.net_flow > 0;

[User] Okay, now refine the results to only include tokens where the smart money ROI is greater than 5 (500%) and the realized ratio is above 0.5.

[Assistant] SELECT tdi.token_symbol, tdi.chain, tdi.volume_24h, smtp.net_flow FROM token_dexpool_info AS tdi JOIN smart_money_token_performance AS smtp ON tdi.token_symbol = smtp.token_symbol AND tdi.chain = smtp.chain WHERE tdi.volume_24h > 1000000 AND smtp.net_flow > 0 AND smtp.roi > 5 AND smtp.realized_ratio > 0.5;

[User] Add the token's current price from the basic info table and its narrative category to the results.

[Assistant] SELECT tdi.token_symbol, tdi.chain, tdi.volume_24h, smtp.net_flow, tbi.price AS current_price, tbi.narrative FROM token_dexpool_info AS tdi JOIN smart_money_token_performance AS smtp ON tdi.token_symbol = smtp.token_symbol AND tdi.chain = smtp.chain JOIN token_basic_info AS tbi ON tdi.token_symbol = tbi.token_symbol AND tdi.chain = tbi.chain WHERE tdi.volume_24h > 1000000 AND smtp.net_flow > 0 AND smtp.roi > 5 AND smtp.realized_ratio > 0.5;

[User] Order the final list by 24-hour trading volume descending and show the top 10.

[Assistant] SELECT tdi.token_symbol, tdi.chain, tdi.volume_24h, smtp.net_flow, tbi.price AS current_price, tbi.narrative FROM token_dexpool_info AS tdi JOIN smart_money_token_performance AS smtp ON tdi.token_symbol = smtp.token_symbol AND tdi.chain = smtp.chain JOIN token_basic_info AS tbi ON tdi.token_symbol = tbi.token_symbol AND tdi.chain = tbi.chain WHERE tdi.volume_24h > 1000000 AND smtp.net_flow > 0 AND smtp.roi > 5 AND smtp.realized_ratio > 0.5 ORDER BY tdi.volume_24h DESC LIMIT 10;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE 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] 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 government_services.employees (
    employee_id character varying(64) NOT NULL, -- unique identifier for the government employee
    agency_id character varying(64) NOT NULL, -- FK to agencies table
    first_name character varying(100) NOT NULL,
    last_name character varying(100) NOT NULL,
    job_title character varying(150) NOT NULL,
    department character varying(100),
    work_email character varying(128) NOT NULL UNIQUE,
    work_phone character varying(32),
    hire_date date NOT NULL,
    termination_date date, -- null if currently employed
    access_level character varying(50), -- Role or permission level
    manager_employee_id character varying(64), -- FK to self for reporting structure
    PRIMARY KEY (employee_id)
)

[User] List the full names of all employees who are currently employed (i.e., have no termination date).

[Assistant] SELECT first_name || ' ' || last_name AS full_name FROM government_services.employees WHERE termination_date IS 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 transportation.vehicles ( vehicle_id text PRIMARY KEY, license_plate text, vin text, make text, model text, year int, type text, capacity int, fuel_type text, status text, depot_id text, acquisition_date date )
CREATE TABLE transportation.drivers ( driver_id text, employee_id text, first_name text, last_name text, license_number text, license_expiry_date date, contact_number text, email text, hire_date date, status text )
CREATE TABLE transportation.routes ( route_id text PRIMARY KEY, route_number text, description text, origin_location_id text, destination_location_id text, distance_km numeric, estimated_duration_minutes int, type text )
CREATE TABLE transportation.trips ( trip_id text PRIMARY KEY, route_id text, vehicle_id text, driver_id text, scheduled_departure timestamp, actual_departure timestamp, scheduled_arrival timestamp, actual_arrival timestamp, origin_location_id text, destination_location_id text, status text, passenger_count int, cargo_manifest_id text )
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, vehicle_id.text, service_date.date, odometer_reading.integer, service_type.text, description.text, cost.numeric, mechanic_name.text, next_service_due_date.date )
CREATE TABLE transportation.bookings ( booking_id text, passenger_id text, trip_id text, seat_number text, booking_time timestamp, status text, fare numeric, payment_transaction_id text, special_requests text )

[User] List maintenance logs including vehicle make, model, service_date, cost, and next_service_due_date for vehicles that are currently 'Active'.

[Assistant]
SELECT ml.log_id,
       v.make,
       v.model,
       ml.service_date,
       ml.cost,
       ml.next_service_due_date
FROM transportation.maintenance_logs ml
JOIN transportation.vehicles v ON ml.vehicle_id = v.vehicle_id
WHERE v.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 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 )

[User] Find documents that have the same document_name but are associated with different cases. Show the document name and the two different case IDs.

[Assistant] SELECT d1.document_name, d1.case_id AS case_id_1, d2.case_id AS case_id_2 FROM legal_services.documents AS d1 JOIN legal_services.documents AS d2 ON d1.document_name = d2.document_name WHERE d1.case_id <> d2.case_id AND d1.document_id < d2.document_id;

[User] Actually, only show pairs where at least one of the documents is of document_type 'Contract'.

[Assistant] SELECT d1.document_name, d1.case_id AS case_id_1, d2.case_id AS case_id_2 FROM legal_services.documents AS d1 JOIN legal_services.documents AS d2 ON d1.document_name = d2.document_name WHERE d1.case_id <> d2.case_id AND d1.document_id < d2.document_id AND (d1.document_type = 'Contract' OR d2.document_type = 'Contract');

[User] Also, only include pairs where both documents were uploaded in the year 2024.

[Assistant] SELECT d1.document_name, d1.case_id AS case_id_1, d2.case_id AS case_id_2 FROM legal_services.documents AS d1 JOIN legal_services.documents AS d2 ON d1.document_name = d2.document_name WHERE d1.case_id <> d2.case_id AND d1.document_id < d2.document_id AND (d1.document_type = 'Contract' OR d2.document_type = 'Contract') AND YEAR(d1.upload_timestamp) = 2024 AND YEAR(d2.upload_timestamp) = 2024;


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.users ( user_id.text, username.text, email.text, password_hash.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.dapps ( dapp_id.text, name.text, description.text, url.text )
CREATE TABLE trading_platform.logs ( log_id.text, user_id.text, action.text, details.text, logged_at.timestamp )

[User] List the names and URLs of all decentralized applications where the description includes the word 'exchange'.

[Assistant]
SELECT d.name, d.url
FROM trading_platform.dapps d
WHERE d.description ILIKE '%exchange%';


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 token_basic_info ( coin_id character varying(100) NOT NULL, -- the id of the token token_name character varying(100) NOT NULL, -- the token's name token_symbol character varying(100) NOT NULL, -- the token's symbol token_address character varying(100) NOT NULL, -- the token's address chain text, -- the chain that the token resides price double precision, -- the current price of the token price_change_percentage_1h double precision, -- change in value divided by the absolute price value of the original token price in 1 hour price_change_percentage_24h double precision, -- change in value divided by the absolute price value of the original token price in 24 hours price_change_percentage_7d double precision, -- change in value divided by the absolute price value of the original token price in 7 days highest_price_24h double precision, -- the highest price of the token in 24 hours lowest_price_24h double precision,  -- the lowest price of the token in 24 hours market_cap double precision, -- the market cap of the token market_cap_rank bigint, -- the rank of the token market cap in desc market_cap_change_percentage_24h text, -- the percentage of market cap changes in 24 hours total_volume text, -- the trade volum of the token both in decentralized exchange(DEX) and centralized exchange(CEX) narrative text, -- the category or narrative of the token trend_rank biging, -- the trending rank of the token, value 1 expresses the most popular token. ,PRIMARY KEY (coin_id, chain) )
CREATE TABLE cex_token_balance ( snapshot_time character varying(32) NOT NULL,  -- the snapshot time of record, converted from original timestamp chain character varying(128) NOT NULL, -- the chain that the token resides address character varying(128) NOT NULL, -- the address that holds the assets, owned by a CEX exchange character varying(512) NOT NULL, -- a centralized exchange name token_address character varying(128) NOT NULL, -- token contract address token_symbol character varying(512), --token symbol balance numeric(38,10), -- token balance usd_value numeric(38,14), -- value of the token held in USD price double precision, --price of the token in USD ,PRIMARY KEY (snapshot_time, exchange, address, chain, token_address) )
CREATE TABLE smart_money_token_performance ( token_address.text, token_symbol.text, pnl.numeric, net_flow.numeric, avg_cost.numeric, price.numeric, realized_ratio.numeric, roi.numeric, chain.text )

[User] Show tokens held by CEX addresses that have a positive ROI from smart money. Display the token symbol, chain, the exchange holding it, the CEX USD value of the holding, and the smart money ROI. Limit the results to the top 10 tokens ranked by smart money ROI in descending order.

[Assistant] SELECT c.token_symbol, c.chain, c.exchange, c.usd_value, s.roi FROM cex_token_balance c JOIN smart_money_token_performance s ON c.token_address = s.token_address AND c.chain = s.chain WHERE s.roi > 0 ORDER BY s.roi DESC LIMIT 10;

[User] Modify the query to also include the token's narrative and its current price from the basic info table.

[Assistant] SELECT c.token_symbol, c.chain, c.exchange, c.usd_value, s.roi, b.narrative, b.price FROM cex_token_balance c JOIN smart_money_token_performance s ON c.token_address = s.token_address AND c.chain = s.chain JOIN token_basic_info b ON c.token_address = b.token_address AND c.chain = b.chain WHERE s.roi > 0 ORDER BY s.roi DESC LIMIT 10;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE narrative_info ( narrative.text, top_3_coins.text, price_change_percentage_1h.numeric, price_change_percentage_24h.numeric, price_change_percentage_7d.numeric, market_cap.numeric, volume_24h.numeric, trend_rank.numeric, token_num.numeric )
  "CREATE TABLE cex_token_balance (",
    "snapshot_time character varying(32) NOT NULL,  -- the snapshot time of record, converted from original timestamp",
    "chain character varying(128) NOT NULL, -- the chain that the token resides",
    "address character varying(128) NOT NULL, -- the address that holds the assets, owned by a CEX",
    "exchange character varying(512) NOT NULL, -- a centralized exchange name",
    "token_address character varying(128) NOT NULL, -- token contract address",
    "token_symbol character varying(512), --token symbol",
    "balance numeric(38,10), -- token balance",
    "usd_value numeric(38,14), -- value of the token held in USD",
    "price double precision, --price of the token in USD",
    ",PRIMARY KEY (snapshot_time, exchange, address, chain, token_address));"

[User] List the top 5 exchanges with the highest total USD value of tokens held on the 'Ethereum' chain for the latest snapshot time.

[Assistant] SELECT exchange, SUM(usd_value) AS TotalUSDValue FROM cex_token_balance WHERE chain = 'Ethereum' AND snapshot_time = (SELECT MAX(snapshot_time) FROM cex_token_balance WHERE chain = 'Ethereum') GROUP BY exchange ORDER BY TotalUSDValue DESC LIMIT 5

[User] Could you also show the number of distinct tokens held by each of these top exchanges?

[Assistant] SELECT exchange, SUM(usd_value) AS TotalUSDValue, COUNT(DISTINCT token_symbol) AS DistinctTokenCount FROM cex_token_balance WHERE chain = 'Ethereum' AND snapshot_time = (SELECT MAX(snapshot_time) FROM cex_token_balance WHERE chain = 'Ethereum') GROUP BY exchange ORDER BY TotalUSDValue DESC LIMIT 5


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE government_services.notifications ( notification_id character varying(64) NOT NULL, citizen_id character varying(64) NOT NULL, application_id character varying(64), message_subject character varying(255), message_body text NOT NULL, channel character varying(30) NOT NULL, sent_at timestamp NOT NULL, status character varying(30) NOT NULL, related_entity_type character varying(50), related_entity_id character varying(64), PRIMARY KEY (notification_id) )

[User] List the application_id and the number of notifications with status 'Pending' for each application.

[Assistant]
SELECT application_id, COUNT(*) AS pending_notification_count
FROM government_services.notifications
WHERE status = 'Pending'
GROUP BY application_id;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE gaming_technology.games ( game_id uuid PRIMARY KEY, title text, developer_id uuid, publisher_id uuid, genre text, release_date date, description text, platform text, engine text, website text )
CREATE TABLE gaming_technology.developers ( developer_id.uuid, name.text, country.text, founded_year.integer, website.text, created_at.timestamptz )
CREATE TABLE gaming_technology.game_sessions ( session_id uuid NOT NULL DEFAULT gen_random_uuid(), player_id uuid NOT NULL, game_id uuid NOT NULL, server_id uuid, start_time timestamp with time zone NOT NULL DEFAULT CURRENT_TIMESTAMP, end_time timestamp with time zone, duration_seconds integer, score integer, session_data jsonb, PRIMARY KEY (session_id) )

[User] Which games were developed by companies in 'United Kingdom'? List the game title and the developer's name.

[Assistant] SELECT T1.title, T2.name FROM gaming_technology.games AS T1 JOIN gaming_technology.developers AS T2 ON T1.developer_id = T2.developer_id WHERE T2.country = 'United Kingdom';

[User] For these games, what is the total duration of all game sessions played? Show game title and total duration in seconds.

[Assistant] SELECT T1.title, SUM(T3.duration_seconds) AS total_duration FROM gaming_technology.games AS T1 JOIN gaming_technology.developers AS T2 ON T1.developer_id = T2.developer_id JOIN gaming_technology.game_sessions AS T3 ON T1.game_id = T3.game_id WHERE T2.country = 'United Kingdom' GROUP BY T1.title;

[User] Only include games where the total session duration is more than 1000000 seconds.

[Assistant] SELECT T1.title, SUM(T3.duration_seconds) AS total_duration FROM gaming_technology.games AS T1 JOIN gaming_technology.developers AS T2 ON T1.developer_id = T2.developer_id JOIN gaming_technology.game_sessions AS T3 ON T1.game_id = T3.game_id WHERE T2.country = 'United Kingdom' GROUP BY T1.title HAVING SUM(T3.duration_seconds) > 1000000;

[User] Order the results by total duration in descending order and limit to the top 5.

[Assistant] SELECT T1.title, SUM(T3.duration_seconds) AS total_duration FROM gaming_technology.games AS T1 JOIN gaming_technology.developers AS T2 ON T1.developer_id = T2.developer_id JOIN gaming_technology.game_sessions AS T3 ON T1.game_id = T3.game_id WHERE T2.country = 'United Kingdom' GROUP BY T1.title HAVING SUM(T3.duration_seconds) > 1000000 ORDER BY total_duration DESC LIMIT 5;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE 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 )

[User] Show me all invoices with their invoice number, client ID, and total amount, along with the issue and due dates. Only include invoices where the total amount is at least 10,000.

[Assistant] SELECT invoice_number, client_id, total_amount, issue_date, due_date FROM legal_services.invoices WHERE total_amount >= 10000;

[User] Can you also add the invoice status and order the results by due date descending?

[Assistant] SELECT invoice_number, client_id, total_amount, issue_date, due_date, status FROM legal_services.invoices WHERE total_amount >= 10000 ORDER BY due_date DESC;

[User] Actually, show only the invoices that have not yet been fully paid.

[Assistant] SELECT invoice_number, client_id, total_amount, issue_date, due_date, status FROM legal_services.invoices WHERE total_amount >= 10000 AND amount_paid < total_amount ORDER BY due_date 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.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) )

[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;


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.notifications (
    notification_id character varying(64) NOT NULL, -- unique identifier for the notification
    recipient_user_id character varying(64) NOT NULL, -- user receiving the notification (FK to users.user_id)
    sender_user_id character varying(64), -- user triggering the notification (FK to users.user_id, can be null for system notifications)
    notification_type character varying(30) NOT NULL, -- type of notification ('like', 'comment', 'follow', 'mention', 'message')
    target_entity_id character varying(64), -- ID of the related entity (post_id, comment_id, user_id, conversation_id)
    target_entity_type character varying(20), -- type of the related entity ('post', 'comment', 'user', 'conversation')
    created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, -- timestamp notification was created
    read_at timestamp, -- timestamp notification was marked as read
    PRIMARY KEY (notification_id)
)
CREATE TABLE social_media.user_settings (
    setting_id character varying(64) NOT NULL, -- unique identifier for the setting entry
    user_id character varying(64) NOT NULL UNIQUE, -- user the settings belong to (FK to users.user_id)
    theme character varying(20) DEFAULT 'light', -- UI theme ('light', 'dark')
    email_notifications_enabled boolean DEFAULT true, -- enable/disable email notifications
    push_notifications_enabled boolean DEFAULT true, -- enable/disable push notifications
    private_profile boolean DEFAULT false, -- is the user profile private
    updated_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, -- timestamp of last setting change
    PRIMARY KEY (setting_id)
)

[User] Show me all users who have been notified by the system (i.e. notifications where the sender_user_id is NULL). Please include their username and the type of each notification.

[Assistant]
SELECT u.username, n.notification_type, n.notification_id
FROM social_media.users u
JOIN social_media.notifications n ON u.user_id = n.recipient_user_id
WHERE n.sender_user_id IS NULL;

[User] I'd like to know which of these users have private profiles. Please add that column to the results.

[Assistant]
SELECT u.username, n.notification_type, n.notification_id, us.private_profile
FROM social_media.users u
JOIN social_media.notifications n ON u.user_id = n.recipient_user_id
JOIN social_media.user_settings us ON u.user_id = us.user_id
WHERE n.sender_user_id IS NULL;

[User] Now, restrict the list to only show system notifications sent after June 1, 2024.

[Assistant]
SELECT u.username, n.notification_type, n.notification_id, us.private_profile
FROM social_media.users u
JOIN social_media.notifications n ON u.user_id = n.recipient_user_id
JOIN social_media.user_settings us ON u.user_id = us.user_id
WHERE n.sender_user_id IS NULL AND n.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 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] 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 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.prescriptions ( prescription_id character varying(64) NOT NULL, record_id character varying(64) NOT NULL, patient_id character varying(64) NOT NULL, doctor_id character varying(64) NOT NULL, medication_id character varying(64) NOT NULL, dosage character varying(100) NOT NULL, frequency character varying(100) NOT NULL, route character varying(50), start_date date NOT NULL, end_date date, quantity_dispensed numeric(10,2), refills_allowed integer NOT NULL DEFAULT 0, prescription_date timestamp with time zone NOT NULL DEFAULT current_timestamp, PRIMARY KEY (prescription_id) )

[User] Show me the record_id, patient_id, prescription_id, medication_id, start_date, and the systolic blood pressure from the associated medical record for all prescriptions.

[Assistant]
SELECT p.prescription_id,
       p.medication_id,
       p.start_date,
       m.record_id,
       m.patient_id,
       (m.vitals->'blood_pressure'->>'systolic')::int AS systolic_bp
FROM healthcare.prescriptions p
JOIN healthcare.medical_records m
  ON p.record_id = m.record_id;

[User] Actually, only include those where the systolic blood pressure is greater than 140.

[Assistant]
SELECT p.prescription_id,
       p.medication_id,
       p.start_date,
       m.record_id,
       m.patient_id,
       (m.vitals->'blood_pressure'->>'systolic')::int AS systolic_bp
FROM healthcare.prescriptions p
JOIN healthcare.medical_records m
  ON p.record_id = m.record_id
WHERE (m.vitals->'blood_pressure'->>'systolic')::int > 140;


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 erc1155_approval_for_all ( block_number bigint, block_timestamp timestamp, transaction_index integer, transaction_hash varchar, log_index integer, contract_address varchar )
CREATE TABLE erc20_balances ( block_number bigint, contract_address text, wallet_address text, amount text, pk text )
CREATE TABLE erc20_balances_historical ( block_number.bigint, contract_address.text, wallet_address.text, amount.text, pk.integer )
CREATE TABLE sui_coins_metadata ( object_id.text, coin_type.text, status.text, decimals.bigint, description.text, icon_url.text, symbol.text, name.text )
CREATE TABLE sui_nfts ( object_id.text, status.text, collection_type.text, package_id.text, previous_transaction.text, display.text, owner.text, name.text )
CREATE TABLE nft_collections (
    blockchain varchar NOT NULL, -- blockchain fields for the functionType  in contract
    contract_address varchar NOT NULL, -- Contract address(with bloom filter)
    name varchar NOT NULL, -- name fields for the functionType  in contract
    symbol varchar NOT NULL, -- symbol fields for the functionType  in contract
    deploy_block_number bigint NOT NULL, -- deploy_block_number fields for the functionType  in contract
    deploy_block_time bigint NOT NULL, -- deploy_block_time fields for the functionType  in contract
    erc_type varchar NOT NULL, -- The type of token
    owner varchar NOT NULL, -- owner fields for the functionType  in contract
    traits varchar NOT NULL, -- traits fields for the functionType  in contract
    description varchar NOT NULL, -- description fields for the functionType  in contract
    slug varchar NOT NULL, -- slug fields for the functionType  in contract
    media_info varchar NOT NULL, -- media_info fields for the functionType  in contract
    image_url varchar NOT NULL, -- image_url fields for the functionType  in contract
    banner_image_url varchar NOT NULL, -- banner_image_url fields for the functionType  in contract
    updated_at bigint NOT NULL, -- updated_at fields for the functionType  in contract
    banner varchar NOT NULL, -- banner fields for the functionType  in contract
    token_count bigint NOT NULL, -- token_count fields for the functionType  in contract
    floor_price varchar NOT NULL, -- floor_price fields for the functionType  in contract
    floor_price_symbol varchar NOT NULL, -- floor_price_symbol fields for the functionType  in contract
    floor_price_contract varchar NOT NULL, -- floor_price_contract fields for the functionType  in contract
    pk integer NOT NULL  -- Partition key for the table(floor(deploy_block_time / 1000 / 86400 / 30))
)
CREATE TABLE token_prices ( uuid text, blockchain text, address text, decimals bigint, symbol text, price real, timestamp timestamp )
CREATE TABLE token_prices_latest (
    blockchain varchar(36) NOT NULL, -- blockchain fields for the functionType  in contract
    address varchar(42) NOT NULL, -- address fields for the functionType  in contract
    decimals bigint NOT NULL, -- decimals fields for the functionType  in contract
    symbol varchar(36) NOT NULL, -- symbol fields for the functionType  in contract
    price real NOT NULL, -- price fields for the functionType  in contract
    timestamp timestamp(6) NOT NULL  -- timestamp fields for the functionType  in contract
)
CREATE TABLE erc20_approval ( block_number bigint NOT NULL, block_timestamp timestamp(6) NOT NULL, transaction_index integer NOT NULL, transaction_hash varchar NOT NULL, log_index integer NOT NULL, contract_address varchar NOT NULL, pk integer NOT NULL )
CREATE TABLE token_balances ( block_number.bigint, block_timestamp.timestamp, tick.text, wallet_address.text, total_supply.decimal, amount.decimal )
CREATE TABLE token_info ( block_timestamp timestamp(3) NOT NULL, block_number bigint NOT NULL, tx_index integer NOT NULL, tx_hash varchar(66) NOT NULL, tick varchar NOT NULL, max_supply decimal(38,0) NOT NULL, lim decimal(38,0) NOT NULL, wlim decimal(38,0) NOT NULL, dec integer NOT NULL, creator varchar(42) NOT NULL )
CREATE TABLE token_activities ( block_timestamp.timestamp, block_number.bigint, tx_index.integer, tx_hash.text, log_index.integer, type.text, tick.text, id.text, amt.decimal, from_address.text, to_address.text )
CREATE TABLE mud_holesky_redstone ( address text, table_id text, key_bytes text, key0 text, key1 text, static_data text, encoded_lengths text, dynamic_data text, is_deleted boolean, block_number bigint, log_index bigint )
CREATE TABLE token_balances_bitcoin ( block_number bigint NOT NULL, block_timestamp timestamp(3) NOT NULL, tick varchar(255) NOT NULL, wallet_address varchar(42) NOT NULL, total_supply varchar NOT NULL, amount varchar NOT NULL )
CREATE TABLE token_info_bitcoin ( block_timestamp timestamp, block_number bigint, tx_index integer, tx_hash text, tick text, max_supply decimal, lim decimal, wlim decimal, dec integer, creator text )
CREATE TABLE token_activities_bitcoin ( block_timestamp timestamp, block_number bigint, tx_index integer, tx_hash varchar, log_index integer, type varchar, tick varchar, id varchar, amt decimal, from_address varchar, to_address varchar )
CREATE TABLE token_activities_avalanche ( block_timestamp timestamp(3) NOT NULL, block_number bigint NOT NULL, tx_index integer NOT NULL, tx_hash varchar(66) NOT NULL, log_index integer NOT NULL, type varchar(20) NOT NULL, tick varchar(255) NOT NULL, id varchar(255) NOT NULL, amt decimal(38,0) NOT NULL, from_address varchar(42) NOT NULL, to_address varchar(42) NOT NULL )
CREATE TABLE token_balances_avalanche ( block_number bigint NOT NULL, block_timestamp timestamp(3) NOT NULL, tick varchar(20) NOT NULL, wallet_address varchar(42) NOT NULL, total_supply decimal(38,0) NOT NULL, amount decimal(38,0) NOT NULL )
CREATE TABLE token_info_avalanche (
    block_timestamp timestamp(3) NOT NULL, -- Timestamp of the block containing the inscription (matches block_timestamp in transactions table)
    block_number bigint NOT NULL, -- Block number containing the inscription (matches block_number in transactions table)
    tx_index integer NOT NULL, -- Index of the transaction containing the inscription (matches transaction_index in transactions table)
    tx_hash varchar(66) NOT NULL, -- Unique identifier of the transaction containing the inscription (matches hash in transactions table)
    tick varchar(20) NOT NULL, -- Ticker:  Identifier of the inscription
    max_supply decimal(38,0) NOT NULL, -- Max supply: Set max supply of the inscription
    lim decimal(38,0) NOT NULL, -- Mint limit: limit per inscription
    wlim decimal(38,0) NOT NULL, -- Limit of each address can maximum mint
    dec integer NOT NULL, -- Decimal for minimum divie
    creator varchar(42) NOT NULL, -- Address originating the inscription (matches from_address in transactions table)
    minted decimal(38,0) NOT NULL, -- Sum of minted amount
    holders decimal(38,0) NOT NULL, -- Count of holders
    txs decimal(38,0) NOT NULL, -- Count of transactions
    updated_timestamp timestamp(3) NOT NULL, -- Timestamp of update
    completed_timestamp timestamp(3) NOT NULL, -- Timestamp of minted completed
    id varchar(255) NOT NULL  -- id fields for the functionType  in contract asc20
)

[User] Show me the current ERC20 token balances for the wallet address '0x1A2b3C4dE5f6A7b8C9d0E1f2A3b4C5d6E7f8A9b0'.

[Assistant] SELECT contract_address, amount FROM erc20_balances WHERE wallet_address = '0x1A2b3C4dE5f6A7b8C9d0E1f2A3b4C5d6E7f8A9b0';

[User] Can you also include the token symbol and name for these balances, and only show tokens where the amount is greater than '1000000000000000000' (representing 1 unit for a token with 18 decimals)?

[Assistant] SELECT b.contract_address, m.symbol, m.name, b.amount FROM erc20_balances AS b JOIN token_metas AS m ON b.contract_address = m.address WHERE b.wallet_address = '0x1A2b3C4dE5f6A7b8C9d0E1f2A3b4C5d6E7f8A9b0' AND CAST(b.amount AS DECIMAL) > 1000000000000000000;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE healthcare.appointments ( appointment_id character varying(64) NOT NULL, patient_id character varying(64) NOT NULL, doctor_id character varying(64) NOT NULL, appointment_time timestamp with time zone NOT NULL, duration_minutes integer NOT NULL, reason text, status character varying(32) NOT NULL, location_id character varying(64), notes text, created_at timestamp with time zone NOT NULL DEFAULT current_timestamp, PRIMARY KEY (appointment_id) )

[User] List appointments with a duration longer than 45 minutes where the 'reason' includes the word 'follow-up'. Show the appointment ID, patient ID, duration, and reason.

[Assistant] SELECT appointment_id, patient_id, duration_minutes, reason FROM healthcare.appointments WHERE duration_minutes > 45 AND reason LIKE '%follow-up%';

[User] Further filter this list to only include appointments created in the year 2023.

[Assistant] SELECT appointment_id, patient_id, duration_minutes, reason FROM healthcare.appointments WHERE duration_minutes > 45 AND reason LIKE '%follow-up%' AND created_at >= '2023-01-01 00:00:00+00' AND created_at < '2024-01-01 00:00:00+00';


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 NOT NULL DEFAULT gen_random_uuid(), game_id uuid NOT NULL, server_name character varying(150), region character varying(50) NOT NULL, ip_address character varying(45), port integer, current_players integer NOT NULL DEFAULT 0, max_players integer NOT NULL, status character varying(30) NOT NULL DEFAULT 'offline', last_heartbeat timestamp with time zone, PRIMARY KEY (server_id) )

[User] For each server, show it alongside another server in the same region that has the closest number of current players.

[Assistant]
SELECT
  s1.server_id AS server_a_id,
  s1.server_name AS server_a_name,
  s2.server_id AS server_b_id,
  s2.server_name AS server_b_name,
  ABS(s1.current_players - s2.current_players) AS player_diff
FROM gaming_technology.servers s1
JOIN gaming_technology.servers s2
  ON s1.region = s2.region
  AND s1.server_id <> s2.server_id
ORDER BY s1.server_id, player_diff
LIMIT 1;

[User] Actually, restrict both servers to those that are currently online.

[Assistant]
SELECT
  s1.server_id AS server_a_id,
  s1.server_name AS server_a_name,
  s2.server_id AS server_b_id,
  s2.server_name AS server_b_name,
  ABS(s1.current_players - s2.current_players) AS player_diff
FROM gaming_technology.servers s1
JOIN gaming_technology.servers s2
  ON s1.region = s2.region
  AND s1.server_id <> s2.server_id
WHERE s1.status = 'online'
  AND s2.status = 'online'
ORDER BY s1.server_id, player_diff
LIMIT 1;

[User] Finally, only show pairs where the difference in current players is less than 10.

[Assistant]
SELECT
  s1.server_id AS server_a_id,
  s1.server_name AS server_a_name,
  s2.server_id AS server_b_id,
  s2.server_name AS server_b_name,
  ABS(s1.current_players - s2.current_players) AS player_diff
FROM gaming_technology.servers s1
JOIN gaming_technology.servers s2
  ON s1.region = s2.region
  AND s1.server_id <> s2.server_id
WHERE s1.status = 'online'
  AND s2.status = 'online'
  AND ABS(s1.current_players - s2.current_players) < 10
ORDER BY s1.server_id, player_diff;


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.reservations (
    reservation_id character varying(64) NOT NULL,  -- unique identifier for the booking
    property_id character varying(64) NOT NULL, -- FK to properties table
    guest_id character varying(64) NOT NULL, -- FK to guests table (primary guest)
    room_id character varying(64), -- FK to rooms table (assigned room, might be null initially)
    room_type_id character varying(64) NOT NULL, -- FK to room_types table (booked room type)
    check_in_date date NOT NULL, -- scheduled check-in date
    check_out_date date NOT NULL, -- scheduled check-out date
    actual_check_in_ts timestamp with time zone, -- actual check-in time
    actual_check_out_ts timestamp with time zone, -- actual check-out time
    num_adults integer NOT NULL, -- number of adults
    num_children integer DEFAULT 0, -- number of children
    status character varying(50) NOT NULL, -- e.g., Pending, Confirmed, CheckedIn, CheckedOut, Cancelled, NoShow
    booking_source character varying(100), -- e.g., Website, OTA (Expedia, Booking.com), Phone, WalkIn
    rate_plan_id character varying(64), -- FK to rate_plans table (optional)
    total_amount numeric(12, 2), -- estimated or final total cost
    amount_paid numeric(12, 2) DEFAULT 0.00, -- amount already paid
    special_requests text, -- specific guest requests for this booking
    created_at timestamp with time zone NOT NULL DEFAULT current_timestamp,
    updated_at timestamp with time zone NOT NULL DEFAULT current_timestamp,
    PRIMARY KEY (reservation_id),
    FOREIGN KEY (property_id) REFERENCES hospitality_technology.properties(property_id),
    FOREIGN KEY (guest_id) REFERENCES hospitality_technology.guests(guest_id),
    FOREIGN KEY (room_id) REFERENCES hospitality_technology.rooms(room_id),
    FOREIGN KEY (room_type_id) REFERENCES hospitality_technology.room_types(room_type_id)
)
CREATE TABLE hospitality_technology.payments (
    payment_id character varying(64) NOT NULL,  -- unique identifier for the payment transaction
    reservation_id character varying(64), -- FK to reservations (if payment is for a stay)
    guest_id character varying(64) NOT NULL, -- FK to guests (who paid)
    bill_id character varying(64), -- FK to bills/invoices this payment applies to
    amount numeric(12,2) NOT NULL, -- amount of the payment
    currency_code character varying(3) NOT NULL, -- ISO currency code (e.g., USD, EUR)
    payment_method character varying(50) NOT NULL, -- e.g., CreditCard, Cash, BankTransfer, Points, Voucher
    card_type character varying(50), -- e.g., Visa, MasterCard, Amex (if CC)
    card_last_four character varying(4), -- last 4 digits of CC (if CC)
    transaction_ref character varying(128), -- reference ID from payment gateway or processor
    payment_timestamp timestamp with time zone NOT NULL DEFAULT current_timestamp, -- when the payment occurred
    status character varying(50) NOT NULL, -- e.g., Pending, Succeeded, Failed, Refunded, Disputed
    staff_id_processed character varying(64), -- FK to staff (who processed the payment)
    notes text, -- notes about the payment
    PRIMARY KEY (payment_id),
    FOREIGN KEY (reservation_id) REFERENCES hospitality_technology.reservations(reservation_id),
    FOREIGN KEY (guest_id) REFERENCES hospitality_technology.guests(guest_id),
    FOREIGN KEY (staff_id_processed) REFERENCES hospitality_technology.staff(staff_id)
)
CREATE TABLE hospitality_technology.reviews (
    review_id character varying(64) NOT NULL,  -- unique identifier for the review
    property_id character varying(64) NOT NULL, -- FK to properties table
    reservation_id character varying(64) UNIQUE, -- FK to reservations (link review to a specific stay, optional but good)
    guest_id character varying(64) NOT NULL, -- FK to guests table
    rating_overall integer, -- overall score (e.g., 1-5 or 1-10)
    rating_cleanliness integer,
    rating_service integer,
    rating_location integer,
    rating_value integer,
    comment text, -- guest's written feedback
    review_source character varying(100), -- e.g., DirectSurvey, TripAdvisor, Google, Booking.com
    review_date timestamp with time zone NOT NULL DEFAULT current_timestamp, -- when the review was submitted
    is_public boolean DEFAULT true, -- whether the review is publicly visible
    staff_response text, -- official response from the property
    response_staff_id character varying(64), -- FK to staff (who responded)
    response_date timestamp with time zone, -- when the response was posted
    PRIMARY KEY (review_id),
    FOREIGN KEY (property_id) REFERENCES hospitality_technology.properties(property_id),
    FOREIGN KEY (reservation_id) REFERENCES hospitality_technology.reservations(reservation_id),
    FOREIGN KEY (guest_id) REFERENCES hospitality_technology.guests(guest_id),
    FOREIGN KEY (response_staff_id) REFERENCES hospitality_technology.staff(staff_id)
)

[User] List all reviews where the cleanliness rating is 3 or below. Include the review comment and the full name of the guest who submitted it.

[Assistant] SELECT T1.comment, T2.first_name, T2.last_name FROM hospitality_technology.reviews AS T1 JOIN hospitality_technology.guests AS T2 ON T1.guest_id = T2.guest_id WHERE T1.rating_cleanliness <= 3;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE 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)
)

[User] How many citizens registered in each year?

[Assistant]
SELECT DATE_PART('year', registration_date) AS year,
       COUNT(*) AS registration_count
FROM government_services.citizens
GROUP BY DATE_PART('year', registration_date)
ORDER BY year;

[User] Actually, include only the years where the count is greater than 500.

[Assistant]
SELECT DATE_PART('year', registration_date) AS year,
       COUNT(*) AS registration_count
FROM government_services.citizens
GROUP BY DATE_PART('year', registration_date)
HAVING COUNT(*) > 500
ORDER BY year;

[User] And sort the results by count descending.

[Assistant]
SELECT DATE_PART('year', registration_date) AS year,
       COUNT(*) AS registration_count
FROM government_services.citizens
GROUP BY DATE_PART('year', registration_date)
HAVING COUNT(*) > 500
ORDER BY registration_count DESC;

[User] Now, also show the average age of citizens for each year at the time of registration.

[Assistant]
SELECT DATE_PART('year', registration_date) AS year,
       COUNT(*) AS registration_count,
       AVG(EXTRACT(YEAR FROM AGE(registration_date, date_of_birth))) AS avg_age
FROM government_services.citizens
GROUP BY DATE_PART('year', registration_date)
HAVING COUNT(*) > 500
ORDER BY registration_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 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] 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';


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.lawyers ( lawyer_id.text, first_name.text, last_name.text, bar_number.text, firm_id.text, email.text, phone.text, specialization.text, hire_date.timestamp, is_partner.boolean )
CREATE TABLE legal_services.law_firms ( firm_id.text, firm_name.text, address.text, phone.text, website.text, founded_date.date, managing_partner_id.text )
CREATE TABLE legal_services.cases (
    case_id character varying(64) NOT NULL,  -- 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)
)
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.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)
)

[User] List the full name and firm name for all lawyers who are not partners.

[Assistant] SELECT T1.first_name, T1.last_name, T2.firm_name FROM legal_services.lawyers AS T1 JOIN legal_services.law_firms AS T2 ON T1.firm_id = T2.firm_id WHERE T1.is_partner = FALSE

[User] Now, only show those non-partner lawyers whose specialization is 'Litigation'.

[Assistant] SELECT T1.first_name, T1.last_name, T2.firm_name FROM legal_services.lawyers AS T1 JOIN legal_services.law_firms AS T2 ON T1.firm_id = T2.firm_id WHERE T1.is_partner = FALSE AND T1.specialization = 'Litigation'

[User] Filter this list to only include those hired after 2021-01-01 and order by hire date.

[Assistant] SELECT T1.first_name, T1.last_name, T2.firm_name FROM legal_services.lawyers AS T1 JOIN legal_services.law_firms AS T2 ON T1.firm_id = T2.firm_id WHERE T1.is_partner = FALSE AND T1.specialization = 'Litigation' AND T1.hire_date > '2021-01-01' ORDER BY T1.hire_date


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE transportation.bookings ( booking_id text, passenger_id text, trip_id text, seat_number text, booking_time timestamp, status text, fare numeric, payment_transaction_id text, special_requests text )

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

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

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

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

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

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


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.lawyers (
    lawyer_id character varying(64) NOT NULL,  -- unique identifier for the lawyer
    first_name character varying(100) NOT NULL, -- lawyer's first name
    last_name character varying(100) NOT NULL, -- lawyer's last name
    bar_number character varying(64) UNIQUE NOT NULL, -- lawyer's bar association number
    firm_id character varying(64), -- FK to law_firms table
    email character varying(128) UNIQUE NOT NULL, -- lawyer's professional email
    phone character varying(32), -- lawyer's contact phone number
    specialization text, -- areas of legal expertise
    hire_date timestamp NOT NULL, -- date the lawyer was hired or joined
    is_partner boolean DEFAULT false, -- flag indicating if the lawyer is a partner
    PRIMARY KEY (lawyer_id)
)
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)
)
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)
)
CREATE TABLE legal_services.time_entries (
    entry_id character varying(64) NOT NULL,  -- unique identifier for the time entry
    case_id character varying(64) NOT NULL, -- FK to cases table
    lawyer_id character varying(64) NOT NULL, -- FK to lawyers table (who performed the work)
    date_worked date NOT NULL, -- date the work was performed
    hours_spent numeric(5, 2) NOT NULL CHECK (hours_spent > 0), -- duration of work in hours (e.g., 1.5 for 1h 30m)
    billing_rate numeric(10, 2) NOT NULL, -- hourly rate applied for this entry
    description text NOT NULL, -- detailed description of the work performed
    is_billable boolean DEFAULT true, -- whether this time entry is billable to the client
    is_billed boolean DEFAULT false, -- whether this entry has been included in an invoice
    invoice_id character varying(64), -- FK to invoices table (once billed)
    created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, -- when the entry was recorded
    PRIMARY KEY (entry_id)
)
CREATE TABLE legal_services.invoices (
    invoice_id character varying(64) NOT NULL,  -- unique identifier for the invoice
    invoice_number character varying(100) UNIQUE NOT NULL, -- user-facing invoice number
    client_id character varying(64) NOT NULL, -- FK to clients table
    case_id character varying(64), -- FK to cases table (optional, could be general retainer)
    issue_date date NOT NULL, -- date the invoice was generated
    due_date date NOT NULL, -- date the payment is due
    total_amount numeric(12, 2) NOT NULL, -- total amount due on the invoice
    amount_paid numeric(12, 2) DEFAULT 0.00, -- amount already paid
    status character varying(50) NOT NULL, -- e.g., Draft, Sent, Paid, Partially Paid, Overdue, Void
    payment_date timestamp, -- date the invoice was fully paid (nullable)
    notes text, -- additional notes or terms on the invoice
    created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
    PRIMARY KEY (invoice_id)
)
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)
)

[User] Show each lawyer's first and last name along with the number of open cases they lead, ordered by the highest number of open cases first.

[Assistant]
SELECT l.first_name, l.last_name, COUNT(c.case_id) AS open_case_count
FROM legal_services.lawyers l
JOIN legal_services.cases c
  ON l.lawyer_id = c.lead_lawyer_id
WHERE c.status = 'Open'
GROUP BY l.first_name, l.last_name
ORDER BY open_case_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.conversations ( conversation_id text PRIMARY KEY, created_at timestamp, last_message_at timestamp, is_group_chat bool, group_name text )

[User] List group conversation names and the count of messages sent in each conversation after '2024-06-01'.

[Assistant] SELECT T1.group_name, COUNT(T2.message_id) FROM social_media.conversations AS T1 JOIN social_media.messages AS T2 ON T1.conversation_id = T2.conversation_id WHERE T1.is_group_chat = TRUE AND T2.sent_at > '2024-06-01' GROUP BY T1.conversation_id, T1.group_name;

[User] Only show conversations that have more than 5 messages sent after that date.

[Assistant] SELECT T1.group_name, COUNT(T2.message_id) FROM social_media.conversations AS T1 JOIN social_media.messages AS T2 ON T1.conversation_id = T2.conversation_id WHERE T1.is_group_chat = TRUE AND T2.sent_at > '2024-06-01' GROUP BY T1.conversation_id, T1.group_name HAVING COUNT(T2.message_id) > 5;