[User] List the citizen IDs for individuals who have both uploaded documents and made payments.

[Assistant] SELECT DISTINCT T1.citizen_id FROM documents AS T1 JOIN payments AS T2 ON T1.citizen_id = T2.citizen_id

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE government_services.documents ( document_id character varying(64) NOT NULL, application_id character varying(64), citizen_id character varying(64) NOT NULL, document_type character varying(100) NOT NULL, file_reference text NOT NULL, upload_timestamp timestamp NOT NULL, expiry_date date, verification_status character varying(30) DEFAULT 'Pending', verified_by_employee_id character varying(64), verification_timestamp timestamp, PRIMARY KEY (document_id) )
CREATE TABLE government_services.payments ( payment_id character varying(64) NOT NULL, application_id character varying(64), citizen_id character varying(64) NOT NULL, service_id character varying(64), amount numeric(12, 2) NOT NULL, currency character varying(3) NOT NULL DEFAULT 'USD', payment_method character varying(50), payment_provider_reference character varying(128), payment_timestamp timestamp NOT NULL, status character varying(30) NOT NULL, notes text, PRIMARY KEY (payment_id) )


[User] Show me each product_type along with the count of products for that type, but only include types where the average base_premium exceeds 500. Order the results by the product count in descending order.

[Assistant]
SELECT product_type,
       COUNT(*) AS product_count
FROM insurance.insurance_products
GROUP BY product_type
HAVING AVG(base_premium) > 500
ORDER BY product_count DESC;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE insurance.insurance_products ( product_id.text, product_name.text, product_type.text, description.text, base_premium.numeric, coverage_details.text, underwriting_rules.text, is_active.boolean, created_at.timestamp, updated_at.timestamp )


[User] Find appointments that are longer than 30 minutes.

[Assistant] SELECT * FROM legal_services.appointments WHERE end_time IS NOT NULL AND start_time IS NOT NULL AND end_time > start_time + INTERVAL '30 minutes'

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
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] Find all wallets created by users in the last 7 days along with any tokens that have a total supply greater than 10 million, showing the wallet address and token details.

[Assistant] SELECT w.address AS wallet_address, t.token_name, t.token_symbol, t.total_supply, t.contract_address FROM web3.wallets w JOIN web3.tokens t ON t.total_supply > 10000000 WHERE w.created_at >= CURRENT_DATE - INTERVAL '7 days';

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE web3.tokens ( token_id character varying(64) NOT NULL, contract_address character varying(128) NOT NULL, token_name character varying(128) NOT NULL, token_symbol character varying(32) NOT NULL, decimals integer NOT NULL, total_supply numeric(38,14) NOT NULL, PRIMARY KEY (token_id) )
CREATE TABLE web3.wallets ( wallet_id character varying(64) NOT NULL, user_id character varying(64) NOT NULL, address character varying(128) NOT NULL, private_key text NOT NULL, created_at timestamp NOT NULL, PRIMARY KEY (wallet_id) )


[User] For each claim, show the corresponding product_type of the insurance product for the related policy.

[Assistant]
SELECT cl.claim_id, ip.product_type
FROM insurance.claims cl
JOIN insurance.policies p ON cl.policy_id = p.policy_id
JOIN insurance.insurance_products ip ON p.product_id = ip.product_id;

[User] Sorry, there is no policies table, I got an error. Can you try joining claims to insurance_products another way?

[Assistant]
-- Unable to join directly since there is no 'policies' table connecting claims to insurance_products. If policy_id equals product_id, you may try:
SELECT claim_id, policy_id, product_type
FROM insurance.claims
JOIN insurance.insurance_products ON claims.policy_id = insurance_products.product_id;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE insurance.customers ( customer_id.text, first_name.text, last_name.text, date_of_birth.date, ssn_hash.text, address_line1.text, address_line2.text, city.text, state.text, zip_code.text, country.text, phone_number.text, email.text, created_at.timestamp, updated_at.timestamp, status.text )
CREATE TABLE insurance.claims ( claim_id.text, policy_id.text, customer_id.text, incident_date.timestamp, reported_date.timestamp, description.text, estimated_loss.numeric, status.text, settlement_amount.numeric, settlement_date.date, claim_handler_id.text, police_report_number.text )
CREATE TABLE insurance.insurance_products ( product_id.text, product_name.text, product_type.text, description.text, base_premium.numeric, coverage_details.text, underwriting_rules.text, is_active.boolean, created_at.timestamp, updated_at.timestamp )
CREATE TABLE insurance.claim_documents ( document_id.text, claim_id.text, document_type.text, file_name.text, file_path.text, file_size_bytes.integer, mime_type.text, uploaded_by.text, uploaded_at.timestamp, description.text )


[User] Find all users who registered with a Yahoo email address, along with their registration dates.

[Assistant] SELECT user_id, username, email, password_hash FROM blockchain.users WHERE email LIKE '%@yahoo.com';

[User] This query doesn't show registration dates. Can you modify it to include the registration date?

[Assistant] I notice the users table doesn't have a registration date column. Would you like me to show other available information from the users table?

[User] Then just show me the count of Yahoo email users instead.

[Assistant] SELECT COUNT(*) as yahoo_user_count FROM blockchain.users WHERE email LIKE '%@yahoo.com';

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE blockchain.blocks ( block_id text, previous_block_id text, timestamp timestamp, nonce integer, merkle_root text, difficulty integer )
CREATE TABLE blockchain.transactions (
    transaction_id character varying(64) NOT NULL,  -- unique identifier for the transaction
    block_id character varying(64) NOT NULL, -- identifier of the block containing the transaction
    sender_address character varying(128) NOT NULL, -- address of the sender
    receiver_address character varying(128) NOT NULL, -- address of the receiver
    amount numeric(38,14) NOT NULL, -- amount transferred
    timestamp timestamp NOT NULL, -- time when the transaction was created
    signature text NOT NULL, -- digital signature of the transaction
    PRIMARY KEY (transaction_id)
)
CREATE TABLE blockchain.addresses ( address_id text PRIMARY KEY, public_key text, balance numeric )
CREATE TABLE blockchain.users ( user_id character varying(64) NOT NULL, username character varying(128) NOT NULL, email character varying(128) NOT NULL, password_hash text NOT NULL, PRIMARY KEY (user_id) )


[User] Find all contracts where the deployer address is the same as the contract address, indicating self-deployed contracts, and show their network IDs and deployment timestamps.

[Assistant] SELECT address, network_id, deployed_at FROM web3.contracts WHERE address = deployer_address;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE web3.contracts ( contract_id character varying(64) NOT NULL, address character varying(128) NOT NULL, abi text NOT NULL, bytecode text NOT NULL, deployer_address character varying(128) NOT NULL, deployed_at timestamp NOT NULL, network_id character varying(64) NOT NULL, status character varying(32) NOT NULL, PRIMARY KEY (contract_id) )


[User] Count the number of law firms founded in each decade. Show the decade (e.g., 1990s, 2000s) and the count.

[Assistant] SELECT CONCAT(FLOOR(EXTRACT(YEAR FROM founded_date) / 10) * 10, 's') AS decade, COUNT(*) AS firm_count FROM law_firms WHERE founded_date IS NOT NULL GROUP BY decade ORDER BY decade;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE legal_services.clients ( client_id text PRIMARY KEY, first_name text, last_name text, company_name text, email text UNIQUE, phone text, address text, date_registered timestamp, status text )
CREATE TABLE legal_services.law_firms ( firm_id text PRIMARY KEY, firm_name text, address text, phone text, website text, founded_date date, managing_partner_id text )
CREATE TABLE legal_services.documents ( document_id text PRIMARY KEY, case_id text, document_name text, document_type text, storage_path text, uploaded_by_lawyer_id text, upload_timestamp timestamp, version int, description text )


[User] How many hashtags have been created in March 2024?

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

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE social_media.users ( user_id text PRIMARY KEY, username text, email text, password_hash text, full_name text, profile_picture_url text, bio text, location text, created_at timestamp, updated_at timestamp, is_verified bool )
CREATE TABLE social_media.hashtags ( hashtag_id text PRIMARY KEY, tag_name text, created_at timestamp )
CREATE TABLE social_media.conversation_participants ( participant_id text PRIMARY KEY, conversation_id text, user_id text, joined_at timestamp, last_read_at timestamp )
CREATE TABLE social_media.notifications ( notification_id text PRIMARY KEY, recipient_user_id text, sender_user_id text, notification_type text, target_entity_id text, target_entity_type text, created_at timestamp, read_at timestamp )


[User] List pairs of citizens who share the same email domain.

[Assistant]
SELECT c1.first_name AS first1,
       c1.last_name AS last1,
       c2.first_name AS first2,
       c2.last_name AS last2,
       SPLIT_PART(c1.contact_email, '@', 2) AS domain
FROM government_services.citizens c1
JOIN government_services.citizens c2
  ON SPLIT_PART(c1.contact_email, '@', 2) = SPLIT_PART(c2.contact_email, '@', 2)
 AND c1.citizen_id < c2.citizen_id
WHERE c1.contact_email IS NOT NULL
  AND c2.contact_email IS NOT NULL;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##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] Get the number of direct reports for each manager, showing manager_id and report_count.

[Assistant]
SELECT manager_id,
       COUNT(*) AS report_count
FROM hospitality_technology.staff
WHERE manager_id IS NOT NULL
GROUP BY manager_id;

[User] Exclude managers who have fewer than 2 direct reports.

[Assistant]
SELECT manager_id,
       COUNT(*) AS report_count
FROM hospitality_technology.staff
WHERE manager_id IS NOT NULL
GROUP BY manager_id
HAVING COUNT(*) >= 2;

[User] Also include the manager's full name alongside their ID.

[Assistant]
SELECT m.staff_id AS manager_id,
       m.first_name || ' ' || m.last_name AS manager_full_name,
       COUNT(s.staff_id) AS report_count
FROM hospitality_technology.staff s
JOIN hospitality_technology.staff m
  ON s.manager_id = m.staff_id
GROUP BY m.staff_id, m.first_name, m.last_name
HAVING COUNT(s.staff_id) >= 2;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE hospitality_technology.staff ( staff_id character varying(64) NOT NULL, property_id character varying(64) NOT NULL, first_name character varying(100) NOT NULL, last_name character varying(100) NOT NULL, position character varying(100) NOT NULL, work_email character varying(255) UNIQUE, work_phone character varying(30), hire_date date NOT NULL, termination_date date, is_active boolean NOT NULL DEFAULT true, access_level integer NOT NULL, manager_id character varying(64), created_at timestamp with time zone NOT NULL DEFAULT current_timestamp, PRIMARY KEY (staff_id), FOREIGN KEY (property_id) REFERENCES hospitality_technology.properties(property_id), FOREIGN KEY (manager_id) REFERENCES hospitality_technology.staff(staff_id) )


[User] Find all medical records where the vitals JSON field contains a blood pressure reading with systolic higher than 140, and show the patient_id, record_date, and vitals.

[Assistant] SELECT patient_id, record_date, vitals FROM healthcare.medical_records WHERE (vitals->>'blood_pressure_systolic')::integer > 140;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE healthcare.medical_records (
    record_id character varying(64) NOT NULL,  -- unique identifier for the medical record entry
    patient_id character varying(64) NOT NULL, -- FK to patients table
    appointment_id character varying(64) UNIQUE, -- FK to appointments table (can be null if record not tied to specific appt)
    doctor_id character varying(64) NOT NULL, -- FK to doctors table (doctor creating the record)
    record_date timestamp with time zone NOT NULL, -- date the record/observation was made
    chief_complaint text, -- patient's primary reason for visit
    present_illness_history text, -- detailed history of the current issue
    past_medical_history text, -- relevant past conditions/surgeries
    physical_examination_notes text, -- findings from the physical exam
    assessment text, -- doctor's assessment/diagnosis summary
    treatment_plan text, -- planned course of action
    vitals jsonb, -- store vitals like BP, HR, Temp as structured JSON
    created_at timestamp with time zone NOT NULL DEFAULT current_timestamp,
    PRIMARY KEY (record_id)
)


[User] What is the total revenue generated by ticket sales at the station with ID 'ST101' for the past month?

[Assistant] I'm sorry, but I can't provide information on the revenue generated by ticket sales as this data is not available in the current database table. The table only contains details about station information such as name, location, and platform count. If you have another question or need assistance with something else related to the station data, I'm happy to help.

System:
You are an SQL statement expert and you can refuse the user's question if the question is not related to the table structure. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE train_station_management.stations ( station_id.text, station_name.text, city.text, state_province.text, country_code.text, address.text, timezone.text, number_of_platforms.integer, created_at.timestamp, last_updated_at.timestamp )


[User] Get the number of agents grouped by status. Return status and agent_count.

[Assistant]
SELECT status,
       COUNT(*) AS agent_count
  FROM insurance.agents
 GROUP BY status;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE insurance.agents ( agent_id text PRIMARY KEY, first_name text, last_name text, agency_name text, license_number text, license_state text, contact_email text, contact_phone text, hire_date date, termination_date date, status text, commission_rate numeric, manager_id text )


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

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

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


[User] List the plan_id, plan_name, and plan_type for all insurance plans where the insurance_provider is 'Humana'.

[Assistant]
SELECT
  plan_id,
  plan_name,
  plan_type
FROM healthcare.insurance_plans
WHERE
  insurance_provider = 'Humana';

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE healthcare.patients ( patient_id text, first_name text, last_name text, date_of_birth date, gender text, address text, phone_number text, email text, emergency_contact_name text, emergency_contact_phone text, created_at timestamp, updated_at timestamp )
CREATE TABLE healthcare.appointments (
    appointment_id character varying(64) NOT NULL, -- unique identifier for the appointment
    patient_id character varying(64) NOT NULL, -- FK to patients table
    doctor_id character varying(64) NOT NULL, -- FK to doctors table
    appointment_time timestamp with time zone NOT NULL, -- date and time of the appointment
    duration_minutes integer NOT NULL, -- expected duration in minutes
    reason text, -- reason for the visit
    status character varying(32) NOT NULL, -- e.g., Scheduled, Completed, Cancelled, No-show
    location_id character varying(64), -- FK to a potential locations/clinics table
    notes text, -- notes related to scheduling
    created_at timestamp with time zone NOT NULL DEFAULT current_timestamp,
    PRIMARY KEY (appointment_id)
)
CREATE TABLE healthcare.medical_records (
    record_id character varying(64) NOT NULL,  -- unique identifier for the medical record entry
    patient_id character varying(64) NOT NULL, -- FK to patients table
    appointment_id character varying(64) UNIQUE, -- FK to appointments table (can be null if record not tied to specific appt)
    doctor_id character varying(64) NOT NULL, -- FK to doctors table (doctor creating the record)
    record_date timestamp with time zone NOT NULL, -- date the record/observation was made
    chief_complaint text, -- patient's primary reason for visit
    present_illness_history text, -- detailed history of the current issue
    past_medical_history text, -- relevant past conditions/surgeries
    physical_examination_notes text, -- findings from the physical exam
    assessment text, -- doctor's assessment/diagnosis summary
    treatment_plan text, -- planned course of action
    vitals jsonb, -- store vitals like BP, HR, Temp as structured JSON
    created_at timestamp with time zone NOT NULL DEFAULT current_timestamp,
    PRIMARY KEY (record_id)
)
CREATE TABLE healthcare.diagnoses ( diagnosis_id.text, record_id.text, patient_id.text, doctor_id.text, diagnosis_code.text, code_type.text, description.text, diagnosis_date.date, status.text, is_chronic.boolean )
CREATE TABLE healthcare.medications ( medication_id text PRIMARY KEY, medication_name text, generic_name text, manufacturer text, ndc_code text, description text )
CREATE TABLE healthcare.prescriptions ( prescription_id character varying(64) NOT NULL, record_id character varying(64) NOT NULL, patient_id character varying(64) NOT NULL, doctor_id character varying(64) NOT NULL, medication_id character varying(64) NOT NULL, dosage character varying(100) NOT NULL, frequency character varying(100) NOT NULL, route character varying(50), start_date date NOT NULL, end_date date, quantity_dispensed numeric(10,2), refills_allowed integer NOT NULL DEFAULT 0, prescription_date timestamp with time zone NOT NULL DEFAULT current_timestamp, PRIMARY KEY (prescription_id) )
CREATE TABLE healthcare.insurance_plans (
    plan_id character varying(64) NOT NULL, -- unique identifier for the insurance plan
    plan_name character varying(200) NOT NULL, -- name of the insurance plan
    insurance_provider character varying(100) NOT NULL, -- name of the insurance company
    plan_type character varying(50), -- e.g., PPO, HMO, EPO
    contact_phone character varying(20), -- provider contact number
    website character varying(255), -- provider website
    PRIMARY KEY (plan_id)
)


[User] Show me all events emitted by contracts where the event name contains 'Approval', along with the contract ID and transaction ID, sorted by emitted timestamp in descending order.

[Assistant] SELECT event_id, contract_id, event_name, transaction_id, emitted_at FROM web3.events WHERE event_name LIKE '%Approval%' ORDER BY emitted_at DESC;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE web3.events (
    event_id character varying(64) NOT NULL,  -- unique identifier for the event
    contract_id character varying(64) NOT NULL, -- identifier of the contract emitting the event
    event_name character varying(128) NOT NULL, -- name of the event
    data text NOT NULL, -- data payload of the event
    emitted_at timestamp NOT NULL, -- time when the event was emitted
    transaction_id character varying(64) NOT NULL, -- identifier of the transaction that triggered the event
    log_index integer NOT NULL, -- index of the event log in the transaction
    PRIMARY KEY (event_id)
)


[User] List the full names and dates of birth for all patients who do not have a phone number on record.

[Assistant] SELECT first_name, last_name, date_of_birth FROM healthcare.patients WHERE phone_number IS NULL OR TRIM(phone_number) = '';

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE healthcare.patients ( patient_id character varying(64) NOT NULL, first_name character varying(100) NOT NULL, last_name character varying(100) NOT NULL, date_of_birth date NOT NULL, gender character varying(10), address text, phone_number character varying(20), email character varying(128) UNIQUE, emergency_contact_name character varying(200), emergency_contact_phone character varying(20), created_at timestamp with time zone NOT NULL DEFAULT current_timestamp, updated_at timestamp with time zone NOT NULL DEFAULT current_timestamp, PRIMARY KEY (patient_id) )
CREATE TABLE healthcare.appointments ( appointment_id.text, patient_id.text, doctor_id.text, appointment_time.timestamp, duration_minutes.integer, reason.text, status.text, location_id.text, notes.text, created_at.timestamp )
CREATE TABLE healthcare.diagnoses (
    diagnosis_id character varying(64) NOT NULL, -- unique identifier for the diagnosis entry
    record_id character varying(64) NOT NULL, -- FK linking to the specific medical record entry
    patient_id character varying(64) NOT NULL, -- FK to patients table
    doctor_id character varying(64) NOT NULL, -- FK to doctors table (diagnosing doctor)
    diagnosis_code character varying(20) NOT NULL, -- standard code (e.g., ICD-10)
    code_type character varying(10) NOT NULL DEFAULT 'ICD-10', -- type of code used
    description text, -- textual description of the diagnosis
    diagnosis_date date NOT NULL, -- date the diagnosis was made
    status character varying(32) NOT NULL, -- e.g., Active, Resolved, Ruled Out
    is_chronic boolean DEFAULT false, -- flag for chronic conditions
    PRIMARY KEY (diagnosis_id)
)
CREATE TABLE healthcare.prescriptions ( prescription_id text, record_id text, patient_id text, doctor_id text, medication_id text, dosage text, frequency text, route text, start_date date, end_date date, quantity_dispensed numeric, refills_allowed integer, prescription_date timestamp )
CREATE TABLE healthcare.insurance_plans ( plan_id text, plan_name text, insurance_provider text, plan_type text, contact_phone text, website text )
CREATE TABLE healthcare.patient_insurance ( patient_insurance_id.text, patient_id.text, plan_id.text, policy_number.text, group_number.text, subscriber_name.text, effective_date.date, expiration_date.date, is_primary.boolean )


[User] How many policies were canceled in the previous month, grouped by cancellation reason?

[Assistant]
SELECT cancellation_reason,
       COUNT(*) AS canceled_count
FROM insurance.policies
WHERE cancellation_date BETWEEN date_trunc('month', CURRENT_DATE) - INTERVAL '1 month'
                             AND date_trunc('month', CURRENT_DATE) - INTERVAL '1 day'
GROUP BY cancellation_reason;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE insurance.policies ( policy_id text, customer_id text, product_id text, agent_id text, policy_number text, start_date date, end_date date, premium_amount numeric, coverage_limit numeric, deductible numeric, status text, issued_at timestamp, cancellation_date date, cancellation_reason text )


[User] Show me all insurance plans that cover more than 10 patients as their primary insurance, along with the provider name and contact information.

[Assistant] SELECT ip.plan_name, ip.insurance_provider, ip.contact_phone, ip.website, COUNT(pi.patient_id) AS patient_count FROM healthcare.insurance_plans ip JOIN healthcare.patient_insurance pi ON ip.plan_id = pi.plan_id WHERE pi.is_primary = true GROUP BY ip.plan_id HAVING COUNT(pi.patient_id) > 10;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE healthcare.patients (
    patient_id character varying(64) NOT NULL,  -- unique identifier for the patient
    first_name character varying(100) NOT NULL, -- patient's first name
    last_name character varying(100) NOT NULL, -- patient's last name
    date_of_birth date NOT NULL, -- patient's date of birth
    gender character varying(10), -- patient's gender (e.g., Male, Female, Other)
    address text, -- patient's home address
    phone_number character varying(20), -- patient's phone number
    email character varying(128) UNIQUE, -- patient's email address
    emergency_contact_name character varying(200), -- name of emergency contact
    emergency_contact_phone character varying(20), -- phone number of emergency contact
    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 (patient_id)
)
CREATE TABLE healthcare.doctors (
    doctor_id character varying(64) NOT NULL,  -- unique identifier for the doctor
    first_name character varying(100) NOT NULL, -- doctor's first name
    last_name character varying(100) NOT NULL, -- doctor's last name
    specialty character varying(100) NOT NULL, -- doctor's medical specialty
    license_number character varying(50) UNIQUE NOT NULL, -- doctor's medical license number
    phone_number character varying(20), -- doctor's contact phone
    email character varying(128) UNIQUE, -- doctor's contact email
    hospital_affiliation_id character varying(64), -- FK to hospitals table (optional)
    created_at timestamp with time zone NOT NULL DEFAULT current_timestamp,
    updated_at timestamp with time zone NOT NULL DEFAULT current_timestamp,
    PRIMARY KEY (doctor_id)
)
CREATE TABLE healthcare.appointments (
    appointment_id character varying(64) NOT NULL, -- unique identifier for the appointment
    patient_id character varying(64) NOT NULL, -- FK to patients table
    doctor_id character varying(64) NOT NULL, -- FK to doctors table
    appointment_time timestamp with time zone NOT NULL, -- date and time of the appointment
    duration_minutes integer NOT NULL, -- expected duration in minutes
    reason text, -- reason for the visit
    status character varying(32) NOT NULL, -- e.g., Scheduled, Completed, Cancelled, No-show
    location_id character varying(64), -- FK to a potential locations/clinics table
    notes text, -- notes related to scheduling
    created_at timestamp with time zone NOT NULL DEFAULT current_timestamp,
    PRIMARY KEY (appointment_id)
)
CREATE TABLE healthcare.diagnoses (
    diagnosis_id character varying(64) NOT NULL, -- unique identifier for the diagnosis entry
    record_id character varying(64) NOT NULL, -- FK linking to the specific medical record entry
    patient_id character varying(64) NOT NULL, -- FK to patients table
    doctor_id character varying(64) NOT NULL, -- FK to doctors table (diagnosing doctor)
    diagnosis_code character varying(20) NOT NULL, -- standard code (e.g., ICD-10)
    code_type character varying(10) NOT NULL DEFAULT 'ICD-10', -- type of code used
    description text, -- textual description of the diagnosis
    diagnosis_date date NOT NULL, -- date the diagnosis was made
    status character varying(32) NOT NULL, -- e.g., Active, Resolved, Ruled Out
    is_chronic boolean DEFAULT false, -- flag for chronic conditions
    PRIMARY KEY (diagnosis_id)
)
CREATE TABLE healthcare.medications (
    medication_id character varying(64) NOT NULL, -- unique identifier for the medication type
    medication_name character varying(255) NOT NULL, -- common or brand name
    generic_name character varying(255), -- generic chemical name
    manufacturer character varying(100), -- drug manufacturer
    ndc_code character varying(20) UNIQUE, -- National Drug Code (optional but useful)
    description text, -- description of the medication
    PRIMARY KEY (medication_id)
)
CREATE TABLE healthcare.prescriptions (
    prescription_id character varying(64) NOT NULL, -- unique identifier for the prescription
    record_id character varying(64) NOT NULL, -- FK linking to the medical record where it was prescribed
    patient_id character varying(64) NOT NULL, -- FK to patients table
    doctor_id character varying(64) NOT NULL, -- FK to prescribing doctor
    medication_id character varying(64) NOT NULL, -- FK to medications table
    dosage character varying(100) NOT NULL, -- e.g., '100mg', '1 tablet'
    frequency character varying(100) NOT NULL, -- e.g., 'Once daily', 'Twice a day with meals'
    route character varying(50), -- e.g., 'Oral', 'Topical', 'Intravenous'
    start_date date NOT NULL, -- date prescription begins
    end_date date, -- date prescription ends (if applicable)
    quantity_dispensed numeric(10,2), -- amount dispensed (e.g., number of tablets)
    refills_allowed integer NOT NULL DEFAULT 0, -- number of allowed refills
    prescription_date timestamp with time zone NOT NULL DEFAULT current_timestamp,
    PRIMARY KEY (prescription_id)
)
CREATE TABLE healthcare.insurance_plans (
    plan_id character varying(64) NOT NULL, -- unique identifier for the insurance plan
    plan_name character varying(200) NOT NULL, -- name of the insurance plan
    insurance_provider character varying(100) NOT NULL, -- name of the insurance company
    plan_type character varying(50), -- e.g., PPO, HMO, EPO
    contact_phone character varying(20), -- provider contact number
    website character varying(255), -- provider website
    PRIMARY KEY (plan_id)
)
CREATE TABLE healthcare.patient_insurance (
    patient_insurance_id character varying(64) NOT NULL, -- unique identifier for this patient-plan link
    patient_id character varying(64) NOT NULL, -- FK to patients table
    plan_id character varying(64) NOT NULL, -- FK to insurance_plans table
    policy_number character varying(100) NOT NULL, -- patient's policy number
    group_number character varying(100), -- group number, if applicable
    subscriber_name character varying(200), -- name of the primary policy holder
    effective_date date NOT NULL, -- date the coverage begins
    expiration_date date, -- date the coverage ends (if known)
    is_primary boolean NOT NULL DEFAULT true, -- indicates if this is the primary insurance
    PRIMARY KEY (patient_insurance_id),
    UNIQUE (patient_id, plan_id, policy_number) -- ensure a patient doesn't have the same policy twice
)


[User] Show me all home loans (loan_id, principal_amount, interest_rate) where the current principal balance is more than 75% of the original principal amount, along with the account_id and employee details (first_name, last_name) of the employee who processed the loan application.

[Assistant] SELECT l.loan_id, l.principal_amount, l.interest_rate, l.account_id, e.first_name, e.last_name FROM financial_services.loans l JOIN financial_services.employees e ON l.account_id = e.employee_id WHERE l.loan_type = 'Home' AND l.current_principal_balance > (l.principal_amount * 0.75)

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE financial_services.transactions ( transaction_id.text, account_id.text, related_account_id.text, transaction_type.text, amount.numeric, currency.text, transaction_date.timestamp, effective_date.date, description.text, status.text, reference_number.text )
CREATE TABLE financial_services.securities ( security_id.text, ticker_symbol.text, isin_code.text, cusip_code.text, security_name.text, security_type.text, exchange.text, currency.text, issuer_name.text, sector.text, last_updated.timestamp )
CREATE TABLE financial_services.market_data ( data_point_id.bigint, security_id.text, data_timestamp.timestamp, open_price.numeric, high_price.numeric, low_price.numeric, close_price.numeric, adjusted_close_price.numeric, volume.bigint, source.text )
CREATE TABLE financial_services.employees ( employee_id.text, first_name.text, last_name.text, job_title.text, department.text, branch_id.text, email.text, phone_extension.text, hire_date.date, termination_date.date, manager_id.text, status.text )
CREATE TABLE financial_services.loans ( loan_id.text, account_id.text, loan_type.text, principal_amount.numeric, current_principal_balance.numeric, interest_rate.numeric, term_months.integer, origination_date.date, maturity_date.date, monthly_payment.numeric, collateral_description.text, status.text )


[User] Show me all cryptocurrency assets that have been traded more than 50 times but have never been traded in quantities greater than 100, along with their average trade price.

[Assistant] SELECT a.asset_id, a.name, a.symbol, COUNT(t.trade_id) AS trade_count, AVG(t.price) AS avg_price FROM trading_platform.assets a JOIN trading_platform.trades t ON a.asset_id = t.asset_id WHERE a.type = 'cryptocurrency' GROUP BY a.asset_id, a.name, a.symbol HAVING COUNT(t.trade_id) > 50 AND MAX(t.quantity) <= 100;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE trading_platform.users ( user_id character varying(64) NOT NULL, username character varying(128) NOT NULL, email character varying(128) NOT NULL, password_hash text NOT NULL, created_at timestamp NOT NULL, PRIMARY KEY (user_id) )
CREATE TABLE trading_platform.wallets ( wallet_id character varying(64) NOT NULL, user_id character varying(64) NOT NULL, address character varying(128) NOT NULL, private_key text NOT NULL, created_at timestamp NOT NULL, PRIMARY KEY (wallet_id) )
CREATE TABLE trading_platform.orders ( order_id character varying(64) NOT NULL, user_id character varying(64) NOT NULL, wallet_id character varying(64) NOT NULL, asset_id character varying(64) NOT NULL, order_type character varying(32) NOT NULL, quantity numeric(38,14) NOT NULL, price numeric(38,14) NOT NULL, status character varying(32) NOT NULL, created_at timestamp NOT NULL, PRIMARY KEY (order_id) )
CREATE TABLE trading_platform.trades ( trade_id character varying(64) NOT NULL, order_id character varying(64) NOT NULL, buyer_id character varying(64) NOT NULL, seller_id character varying(64) NOT NULL, asset_id character varying(64) NOT NULL, quantity numeric(38,14) NOT NULL, price numeric(38,14) NOT NULL, traded_at timestamp NOT NULL, PRIMARY KEY (trade_id) )
CREATE TABLE trading_platform.assets ( asset_id character varying(64) NOT NULL, name character varying(128) NOT NULL, symbol character varying(32) NOT NULL, type character varying(32) NOT NULL, PRIMARY KEY (asset_id) )
CREATE TABLE trading_platform.utxos ( utxo_id character varying(64) NOT NULL, transaction_id character varying(64) NOT NULL, output_index integer NOT NULL, address character varying(128) NOT NULL, amount numeric(38,14) NOT NULL, spent boolean NOT NULL, PRIMARY KEY (utxo_id) )
CREATE TABLE trading_platform.dapps ( dapp_id character varying(64) NOT NULL, name character varying(128) NOT NULL, description text NOT NULL, url character varying(256) NOT NULL, PRIMARY KEY (dapp_id) )
CREATE TABLE trading_platform.peers ( peer_id character varying(64) NOT NULL, ip_address character varying(15) NOT NULL, port integer NOT NULL, last_seen timestamp NOT NULL, PRIMARY KEY (peer_id) )
CREATE TABLE trading_platform.metadata ( metadata_id character varying(64) NOT NULL, asset_id character varying(64) NOT NULL, key character varying(128) NOT NULL, value text NOT NULL, PRIMARY KEY (metadata_id) )
CREATE TABLE trading_platform.kyc_audit ( kyc_audit_id character varying(64) NOT NULL, user_id character varying(64) NOT NULL, status character varying(32) NOT NULL, reviewed_at timestamp NOT NULL, PRIMARY KEY (kyc_audit_id) )
CREATE TABLE trading_platform.notifications ( notification_id character varying(64) NOT NULL, user_id character varying(64) NOT NULL, message text NOT NULL, sent_at timestamp NOT NULL, read_at timestamp, PRIMARY KEY (notification_id) )


[User] Show me wallet addresses that hold more than 1000 of any ERC20 token, along with the token symbol and amount, sorted by amount in descending order.

[Assistant] SELECT b.wallet_address, t.symbol, b.amount FROM erc20_balances b JOIN sui_coins_metadata t ON b.contract_address = t.coin_type WHERE CAST(b.amount AS decimal) > 1000 ORDER BY CAST(b.amount AS decimal) DESC;

[User] Can you also include the current price of each token from the token_prices_latest table?

[Assistant] SELECT b.wallet_address, t.symbol, b.amount, p.price FROM erc20_balances b JOIN sui_coins_metadata t ON b.contract_address = t.coin_type JOIN token_prices_latest p ON b.contract_address = p.address WHERE CAST(b.amount AS decimal) > 1000 ORDER BY CAST(b.amount AS decimal) DESC;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE erc1155_approval_for_all (
    block_number bigint NOT NULL, -- Block number containing the transaction
    block_timestamp timestamp(3) NOT NULL, -- Timestamp of the block containing the transaction
    transaction_index integer NOT NULL, -- Index of the transaction within the block
    transaction_hash varchar(66) NOT NULL, -- Transaction hash
    log_index integer NOT NULL, -- Log index
    contract_address varchar(42) NOT NULL  -- Event contract address
)
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 NOT NULL, contract_address varchar NOT NULL, wallet_address varchar NOT NULL, amount varchar NOT NULL, pk integer NOT NULL )
CREATE TABLE nft_holders ( block_number bigint, contract_address varchar, wallet_address varchar, token_id varchar, contract_type varchar, amount varchar, pk varchar )
CREATE TABLE sui_coins_metadata ( object_id varchar, coin_type varchar, status varchar, decimals bigint, description varchar, icon_url varchar, symbol varchar, name varchar )
CREATE TABLE nft_metadata (
    blockchain varchar NOT NULL, -- blockchain fields for the functionType  in contract
    contract_address varchar NOT NULL, -- Contract address(with bloom filter)
    token_id varchar NOT NULL, -- The number of the token
    contract_name varchar NOT NULL, -- contract_name fields for the functionType  in contract
    erc_type varchar NOT NULL, -- The type of token
    amount bigint NOT NULL, -- amount fields for the functionType  in contract
    minter varchar NOT NULL, -- minter fields for the functionType  in contract
    owner varchar NOT NULL, -- owner fields for the functionType  in contract
    mint_block_number bigint NOT NULL, -- mint_block_number fields for the functionType  in contract
    mint_time bigint NOT NULL, -- mint_time fields for the functionType  in contract
    mint_transaction_hash varchar NOT NULL, -- mint_transaction_hash fields for the functionType  in contract
    mint_price varchar NOT NULL, -- mint_price fields for the functionType  in contract
    token_uri varchar NOT NULL, -- token_uri fields for the functionType  in contract
    metadata varchar NOT NULL, -- metadata fields for the functionType  in contract
    name varchar NOT NULL, -- name fields for the functionType  in contract
    image_uri varchar NOT NULL, -- image_uri fields for the functionType  in contract
    traits varchar NOT NULL, -- traits fields for the functionType  in contract
    updated_at bigint NOT NULL, -- updated_at fields for the functionType  in contract
    status varchar NOT NULL, -- status fields for the functionType  in contract
    rarity_score real NOT NULL, -- rarity_score fields for the functionType  in contract
    rarity_rank integer NOT NULL, -- rarity_rank fields for the functionType  in contract
    unique_attribute_count integer NOT NULL, -- unique_attribute_count fields for the functionType  in contract
    pk integer NOT NULL  -- Partition key for the table(floor(mint_time / 1000 / 86400 / 30))
)
CREATE TABLE token_prices_latest ( blockchain varchar, address varchar, decimals bigint, symbol varchar, price real, timestamp timestamp )
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 mud_holesky_redstone (
    address varchar NOT NULL, -- address fields for the functionType  in contract
    table_id varchar NOT NULL, -- table_id fields for the functionType  in contract
    key_bytes varchar NOT NULL, -- key_bytes fields for the functionType  in contract
    key0 varchar NOT NULL, -- key0 fields for the functionType  in contract
    key1 varchar NOT NULL, -- key1 fields for the functionType  in contract
    static_data varchar NOT NULL, -- static_data fields for the functionType  in contract
    encoded_lengths varchar NOT NULL, -- encoded_lengths fields for the functionType  in contract
    dynamic_data varchar NOT NULL, -- dynamic_data fields for the functionType  in contract
    is_deleted boolean NOT NULL, -- is_deleted fields for the functionType  in contract
    block_number bigint NOT NULL, -- Block number uniquely identifying the block
    log_index bigint NOT NULL  -- Index of the log within the transaction
)
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_balances_avalanche (
    block_number bigint NOT NULL, -- Block number containing the transaction
    block_timestamp timestamp(3) NOT NULL, -- Block timestamp containing the transaction
    tick varchar(20) NOT NULL, -- Ticker: Identifier of the inscription
    wallet_address varchar(42) NOT NULL, -- Address of owner
    total_supply decimal(38,0) NOT NULL, -- Max supply: Set max supply of the inscription
    amount decimal(38,0) NOT NULL  -- The balance of wallet balance at the corresponding block height
)
CREATE TABLE token_info_avalanche ( 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, minted decimal, holders decimal, txs decimal, updated_timestamp timestamp, completed_timestamp timestamp, id text )


[User] Show all rooms that are on floor 3.

[Assistant] SELECT room_id, property_id, room_number FROM hospitality_technology.rooms WHERE floor = 3;

[User] For these rooms, include the property name and room number.

[Assistant] SELECT r.room_number, p.property_name FROM hospitality_technology.rooms AS r JOIN hospitality_technology.properties AS p ON r.property_id = p.property_id WHERE r.floor = 3;

[User] Also, include the type name and current status for each room.

[Assistant] SELECT r.room_number, p.property_name, rt.type_name, r.status FROM hospitality_technology.rooms AS r JOIN hospitality_technology.properties AS p ON r.property_id = p.property_id JOIN hospitality_technology.room_types AS rt ON r.room_type_id = rt.room_type_id AND r.property_id = rt.property_id WHERE r.floor = 3;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE hospitality_technology.properties ( property_id text, property_name text, address_line1 text, address_line2 text, city text, state_province text, postal_code text, country_code text, phone_number text, email_address text, property_type text, star_rating numeric, timezone text, manager_staff_id text, created_at timestamp, updated_at timestamp )
CREATE TABLE hospitality_technology.rooms ( room_id text, property_id text, room_number text, room_type_id text, floor integer, status text, is_smoking boolean, features text, current_condition text, last_cleaned_at timestamp )
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 )


[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 SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##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 route that originates from a location of type 'Port', list the route number, the name of the origin location, and the total distance accumulated from all completed trips on this route.

[Assistant]
SELECT
  r.route_number,
  l_origin.name AS origin_location_name,
  SUM(t.distance_km) AS total_accumulated_distance
FROM transportation.routes AS r
JOIN transportation.locations AS l_origin
  ON r.origin_location_id = l_origin.location_id
JOIN transportation.trips AS t
  ON r.route_id = t.route_id
WHERE
  l_origin.type = 'Port' AND t.status = 'Completed'
GROUP BY
  r.route_id,
  r.route_number,
  l_origin.name;

[User] Now, only include routes where the accumulated distance is greater than 5000 kilometers and order the results by accumulated distance descending.

[Assistant]
SELECT
  r.route_number,
  l_origin.name AS origin_location_name,
  SUM(t.distance_km) AS total_accumulated_distance
FROM transportation.routes AS r
JOIN transportation.locations AS l_origin
  ON r.origin_location_id = l_origin.location_id
JOIN transportation.trips AS t
  ON r.route_id = t.route_id
WHERE
  l_origin.type = 'Port' AND t.status = 'Completed'
GROUP BY
  r.route_id,
  r.route_number,
  l_origin.name
HAVING
  SUM(t.distance_km) > 5000
ORDER BY
  total_accumulated_distance DESC;

[User] Also include the number of completed trips for each of these routes and filter further to only show routes that have had more than 5 completed trips.

[Assistant]
SELECT
  r.route_number,
  l_origin.name AS origin_location_name,
  SUM(t.distance_km) AS total_accumulated_distance,
  COUNT(t.trip_id) AS completed_trip_count
FROM transportation.routes AS r
JOIN transportation.locations AS l_origin
  ON r.origin_location_id = l_origin.location_id
JOIN transportation.trips AS t
  ON r.route_id = t.route_id
WHERE
  l_origin.type = 'Port' AND t.status = 'Completed'
GROUP BY
  r.route_id,
  r.route_number,
  l_origin.name
HAVING
  SUM(t.distance_km) > 5000 AND COUNT(t.trip_id) > 5
ORDER BY
  total_accumulated_distance DESC;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE transportation.vehicles ( vehicle_id text PRIMARY KEY, license_plate text, vin text, make text, model text, year int, type text, capacity int, fuel_type text, status text, depot_id text, acquisition_date date )
CREATE TABLE transportation.drivers ( driver_id text PRIMARY KEY, employee_id text, first_name text, last_name text, license_number text, license_expiry_date date, contact_number text, email text, hire_date date, status text )
CREATE TABLE transportation.routes ( route_id text PRIMARY KEY, route_number text, description text, origin_location_id text, destination_location_id text, distance_km numeric, estimated_duration_minutes int, type text )
CREATE TABLE transportation.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 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.bookings ( booking_id text PRIMARY KEY, passenger_id text, trip_id text, seat_number text, booking_time timestamp, status text, fare numeric, payment_transaction_id text, special_requests text )


[User] Show me the number of approval-for-all events for each ERC1155 contract in the erc1155_approval_for_all table.

[Assistant] SELECT contract_address, COUNT(*) AS approval_count FROM erc1155_approval_for_all GROUP BY contract_address;

[User] Can you also include the number of unique wallets currently holding NFTs from each ERC1155 contract by joining with nft_holders?

[Assistant] SELECT a.contract_address, COUNT(*) AS approval_count, COUNT(DISTINCT h.wallet_address) AS unique_holder_count FROM erc1155_approval_for_all a LEFT JOIN nft_holders h ON h.contract_address = a.contract_address AND h.contract_type = 'ERC1155' GROUP BY a.contract_address;

[User] Filter the results to only include contracts where the approval_count is greater than 20 and unique_holder_count is more than 5.

[Assistant] SELECT a.contract_address, COUNT(*) AS approval_count, COUNT(DISTINCT h.wallet_address) AS unique_holder_count FROM erc1155_approval_for_all a LEFT JOIN nft_holders h ON h.contract_address = a.contract_address AND h.contract_type = 'ERC1155' GROUP BY a.contract_address HAVING COUNT(*) > 20 AND COUNT(DISTINCT h.wallet_address) > 5;

[User] Order the results by approval_count descending and limit to the top 5 contracts.

[Assistant] SELECT a.contract_address, COUNT(*) AS approval_count, COUNT(DISTINCT h.wallet_address) AS unique_holder_count FROM erc1155_approval_for_all a LEFT JOIN nft_holders h ON h.contract_address = a.contract_address AND h.contract_type = 'ERC1155' GROUP BY a.contract_address HAVING COUNT(*) > 20 AND COUNT(DISTINCT h.wallet_address) > 5 ORDER BY approval_count DESC LIMIT 5;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE erc1155_approval_for_all (
    block_number bigint NOT NULL, -- Block number containing the transaction
    block_timestamp timestamp(3) NOT NULL, -- Timestamp of the block containing the transaction
    transaction_index integer NOT NULL, -- Index of the transaction within the block
    transaction_hash varchar(66) NOT NULL, -- Transaction hash
    log_index integer NOT NULL, -- Log index
    contract_address varchar(42) NOT NULL  -- Event contract address
)
CREATE TABLE erc20_balances_historical ( block_number bigint NOT NULL, contract_address varchar NOT NULL, wallet_address varchar NOT NULL, amount varchar NOT NULL, pk integer NOT NULL )
CREATE TABLE nft_holders ( block_number bigint NOT NULL, contract_address varchar NOT NULL, wallet_address varchar NOT NULL, token_id varchar NOT NULL, contract_type varchar NOT NULL, amount varchar NOT NULL, pk varchar NOT NULL )
CREATE TABLE nft_holder_historical ( block_number bigint NOT NULL, contract_address varchar NOT NULL, wallet_address varchar NOT NULL, token_id varchar NOT NULL, contract_type varchar NOT NULL, amount varchar NOT NULL, pk integer NOT NULL )
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_metadata ( blockchain text, contract_address text, token_id text, contract_name text, erc_type text, amount bigint, minter text, owner text, mint_block_number bigint, mint_time bigint, mint_transaction_hash text, mint_price text, token_uri text, metadata text, name text, image_uri text, traits text, updated_at bigint, status text, rarity_score real, rarity_rank integer, unique_attribute_count integer, pk integer )
CREATE TABLE nft_collections ( blockchain varchar NOT NULL, contract_address varchar NOT NULL, name varchar NOT NULL, symbol varchar NOT NULL, deploy_block_number bigint NOT NULL, deploy_block_time bigint NOT NULL, erc_type varchar NOT NULL, owner varchar NOT NULL, traits varchar NOT NULL, description varchar NOT NULL, slug varchar NOT NULL, media_info varchar NOT NULL, image_url varchar NOT NULL, banner_image_url varchar NOT NULL, updated_at bigint NOT NULL, banner varchar NOT NULL, token_count bigint NOT NULL, floor_price varchar NOT NULL, floor_price_symbol varchar NOT NULL, floor_price_contract varchar NOT NULL, pk integer NOT NULL )
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_info (
    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 NOT NULL, -- Token tick
    max_supply decimal(38,0) NOT NULL, -- Max supply
    lim decimal(38,0) NOT NULL, -- Limit of each mint
    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)
)
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 text, log_index integer, type text, tick text, id text, amt decimal, from_address text, to_address text )
CREATE TABLE token_activities_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)
    log_index integer NOT NULL, -- Index of the log within the transaction
    type varchar(20) NOT NULL, -- Operation: Type of event (deploy, mint, transfer, list)
    tick varchar(255) NOT NULL, -- Ticker: Identifier of the inscription
    id varchar(255) NOT NULL, -- Unique identifier of the inscription
    amt decimal(38,0) NOT NULL, -- Amount to mint: States the amount of the inscription to operation. When operation is mint, has to be less or equal to "lim"
    from_address varchar(42) NOT NULL, -- Address sending the inscription
    to_address varchar(42) NOT NULL  -- Address receiving the inscription
)
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 text, tick text, max_supply decimal, lim decimal, wlim decimal, dec integer, creator text, minted decimal, holders decimal, txs decimal, updated_timestamp timestamp, completed_timestamp timestamp, id text )


[User] Calculate the total quantity traded for each asset, showing the asset name and symbol.

[Assistant] SELECT T1.name, T1.symbol, SUM(T2.quantity) FROM trading_platform.assets AS T1 JOIN trading_platform.trades AS T2 ON T1.asset_id = T2.asset_id GROUP BY 1, 2;

[User] Only show assets where the total quantity traded is more than 5000.

[Assistant] SELECT T1.name, T1.symbol, SUM(T2.quantity) FROM trading_platform.assets AS T1 JOIN trading_platform.trades AS T2 ON T1.asset_id = T2.asset_id GROUP BY 1, 2 HAVING SUM(T2.quantity) > 5000;

[User] Actually, instead of total quantity, show the average trade price for each asset.

[Assistant] SELECT T1.name, T1.symbol, AVG(T2.price) FROM trading_platform.assets AS T1 JOIN trading_platform.trades AS T2 ON T1.asset_id = T2.asset_id GROUP BY 1, 2;

[User] Sort those assets by the average price in descending order.

[Assistant] SELECT T1.name, T1.symbol, AVG(T2.price) FROM trading_platform.assets AS T1 JOIN trading_platform.trades AS T2 ON T1.asset_id = T2.asset_id GROUP BY 1, 2 ORDER BY AVG(T2.price) DESC;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE trading_platform.users ( user_id.text, username.text, email.text, password_hash.text, created_at.timestamp )
CREATE TABLE trading_platform.wallets ( wallet_id text, user_id text, address text, private_key text, created_at timestamp )
CREATE TABLE trading_platform.orders ( order_id text, user_id text, wallet_id text, asset_id text, order_type text, quantity numeric, price numeric, status text, created_at timestamp )
CREATE TABLE trading_platform.trades ( trade_id character varying(64) NOT NULL, order_id character varying(64) NOT NULL, buyer_id character varying(64) NOT NULL, seller_id character varying(64) NOT NULL, asset_id character varying(64) NOT NULL, quantity numeric(38,14) NOT NULL, price numeric(38,14) NOT NULL, traded_at timestamp NOT NULL, PRIMARY KEY (trade_id) )
CREATE TABLE trading_platform.assets ( asset_id text, name text, symbol text, type text )
CREATE TABLE trading_platform.dapps ( dapp_id text, name text, description text, url text )
CREATE TABLE trading_platform.peers ( peer_id.text, ip_address.text, port.integer, last_seen.timestamp )
CREATE TABLE trading_platform.metadata ( metadata_id character varying(64) NOT NULL, asset_id character varying(64) NOT NULL, key character varying(128) NOT NULL, value text NOT NULL, PRIMARY KEY (metadata_id) )
CREATE TABLE trading_platform.kyc_audit ( kyc_audit_id.text, user_id.text, status.text, reviewed_at.timestamp )
CREATE TABLE trading_platform.logs ( log_id text PRIMARY KEY, user_id text, action text, details text, logged_at timestamp )
CREATE TABLE trading_platform.notifications ( notification_id text, user_id text, message text, sent_at timestamp, read_at timestamp )


[User] Show me all customers who have missing contact information (either phone number or email is null), along with their state and city.

[Assistant] SELECT first_name, last_name, state, city FROM insurance.customers WHERE phone_number IS NULL OR email IS NULL;

[User] Now filter these to only show customers from Florida or New York who were created in the last 2 years.

[Assistant] SELECT first_name, last_name, state, city FROM insurance.customers WHERE (phone_number IS NULL OR email IS NULL) AND state IN ('Florida', 'New York') AND created_at >= CURRENT_DATE - INTERVAL '2 years';

[User] I also want to see when these customers were last updated (updated_at field).

[Assistant] SELECT first_name, last_name, state, city, updated_at FROM insurance.customers WHERE (phone_number IS NULL OR email IS NULL) AND state IN ('Florida', 'New York') AND created_at >= CURRENT_DATE - INTERVAL '2 years';

[User] Finally, order the results by state first, then by the most recently updated customers first.

[Assistant] SELECT first_name, last_name, state, city, updated_at FROM insurance.customers WHERE (phone_number IS NULL OR email IS NULL) AND state IN ('Florida', 'New York') AND created_at >= CURRENT_DATE - INTERVAL '2 years' ORDER BY state ASC, updated_at DESC;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE insurance.customers (
    customer_id character varying(64) NOT NULL,  -- unique identifier for the customer
    first_name character varying(100) NOT NULL, -- customer's first name
    last_name character varying(100) NOT NULL, -- customer's last name
    date_of_birth date NOT NULL, -- customer's date of birth
    ssn_hash character varying(128), -- Hashed social security number (or national ID)
    address_line1 character varying(255) NOT NULL,
    address_line2 character varying(255),
    city character varying(100) NOT NULL,
    state character varying(50) NOT NULL,
    zip_code character varying(20) NOT NULL,
    country character varying(50) NOT NULL DEFAULT 'USA',
    phone_number character varying(30),
    email character varying(128) UNIQUE, -- unique email address
    created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, -- when the customer record was created
    updated_at timestamp, -- when the customer record was last updated
    status character varying(20) NOT NULL DEFAULT 'Active', -- e.g., Active, Inactive, Prospect
    PRIMARY KEY (customer_id)
)


[User] Show me all customers who have missing contact information (either phone number or email is null), along with their state and city.

[Assistant] SELECT first_name, last_name, state, city FROM insurance.customers WHERE phone_number IS NULL OR email IS NULL;

[User] Now filter these to only show customers from Florida or New York who were created in the last year.

[Assistant] SELECT first_name, last_name, state, city FROM insurance.customers WHERE (phone_number IS NULL OR email IS NULL) AND state IN ('Florida', 'New York') AND created_at >= CURRENT_DATE - INTERVAL '1 year';

[User] I also want to see when these customers were last updated (updated_at field).

[Assistant] SELECT first_name, last_name, state, city, updated_at FROM insurance.customers WHERE (phone_number IS NULL OR email IS NULL) AND state IN ('Florida', 'New York') AND created_at >= CURRENT_DATE - INTERVAL '1 year';

[User] Finally, order the results by state first, then by the most recently updated customers first.

[Assistant] SELECT first_name, last_name, state, city, updated_at FROM insurance.customers WHERE (phone_number IS NULL OR email IS NULL) AND state IN ('Florida', 'New York') AND created_at >= CURRENT_DATE - INTERVAL '1 year' ORDER BY state, updated_at DESC;


[User] List all pairs of tokens (show token_id for both) that share the same contract address, excluding pairs where the token_id is the same.

[Assistant] SELECT t1.token_id AS token_id1, t2.token_id AS token_id2, t1.contract_address FROM web3.tokens AS t1 JOIN web3.tokens AS t2 ON t1.contract_address = t2.contract_address WHERE t1.token_id < t2.token_id;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE web3.tokens ( token_id character varying(64) NOT NULL, contract_address character varying(128) NOT NULL, token_name character varying(128) NOT NULL, token_symbol character varying(32) NOT NULL, decimals integer NOT NULL, total_supply numeric(38,14) NOT NULL, PRIMARY KEY (token_id) )


[User] Provide a report of each user with their username and the count of all log entries from the last 30 days.

[Assistant]
SELECT u.user_id, u.username, COUNT(l.log_id) AS log_count
FROM trading_platform.users u
LEFT JOIN trading_platform.logs l
  ON u.user_id = l.user_id
  AND l.logged_at >= CURRENT_DATE - INTERVAL '30 days'
GROUP BY u.user_id, u.username;

[User] Actually, show only logs where the action includes the word 'trade'.

[Assistant]
SELECT u.user_id, u.username, COUNT(l.log_id) AS log_count
FROM trading_platform.users u
JOIN trading_platform.logs l
  ON u.user_id = l.user_id
WHERE l.logged_at >= CURRENT_DATE - INTERVAL '30 days'
  AND l.action ILIKE '%trade%'
GROUP BY u.user_id, u.username;

[User] Also include the earliest log date for each user in that period.

[Assistant]
SELECT u.user_id,
       u.username,
       COUNT(l.log_id) AS log_count,
       MIN(l.logged_at) AS first_log_date
FROM trading_platform.users u
JOIN trading_platform.logs l
  ON u.user_id = l.user_id
WHERE l.logged_at >= CURRENT_DATE - INTERVAL '30 days'
  AND l.action ILIKE '%trade%'
GROUP BY u.user_id, u.username;

[User] Finally, sort the results by log_count descending and limit to the top 5 users.

[Assistant]
SELECT u.user_id,
       u.username,
       COUNT(l.log_id) AS log_count,
       MIN(l.logged_at) AS first_log_date
FROM trading_platform.users u
JOIN trading_platform.logs l
  ON u.user_id = l.user_id
WHERE l.logged_at >= CURRENT_DATE - INTERVAL '30 days'
  AND l.action ILIKE '%trade%'
GROUP BY u.user_id, u.username
ORDER BY log_count DESC
LIMIT 5;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE trading_platform.users (
    user_id character varying(64) NOT NULL,  -- unique identifier for the user
    username character varying(128) NOT NULL, -- username of the user
    email character varying(128) NOT NULL, -- email address of the user
    password_hash text NOT NULL, -- hashed password of the user
    created_at timestamp NOT NULL, -- time when the user account was created
    PRIMARY KEY (user_id)
)
CREATE TABLE trading_platform.orders (
    order_id character varying(64) NOT NULL,  -- unique identifier for the order
    user_id character varying(64) NOT NULL, -- identifier of the user placing the order
    wallet_id character varying(64) NOT NULL, -- identifier of the wallet used for the order
    asset_id character varying(64) NOT NULL, -- identifier of the asset being traded
    order_type character varying(32) NOT NULL, -- type of the order (e.g., buy, sell)
    quantity numeric(38,14) NOT NULL, -- quantity of the asset in the order
    price numeric(38,14) NOT NULL, -- price per unit of the asset
    status character varying(32) NOT NULL, -- status of the order (e.g., open, filled, canceled)
    created_at timestamp NOT NULL, -- time when the order was created
    PRIMARY KEY (order_id)
)
CREATE TABLE trading_platform.utxos (
    utxo_id character varying(64) NOT NULL,  -- unique identifier for the UTXO
    transaction_id character varying(64) NOT NULL, -- identifier of the transaction that created the UTXO
    output_index integer NOT NULL, -- index of the output in the transaction
    address character varying(128) NOT NULL, -- address that can spend the UTXO
    amount numeric(38,14) NOT NULL, -- amount of the asset in the UTXO
    spent boolean NOT NULL, -- whether the UTXO has been spent
    PRIMARY KEY (utxo_id)
)
CREATE TABLE trading_platform.dapps (
    dapp_id character varying(64) NOT NULL,  -- unique identifier for the DApp
    name character varying(128) NOT NULL, -- name of the DApp
    description text NOT NULL, -- description of the DApp
    url character varying(256) NOT NULL, -- URL of the DApp
    PRIMARY KEY (dapp_id)
)
CREATE TABLE trading_platform.peers (
    peer_id character varying(64) NOT NULL,  -- unique identifier for the peer
    ip_address character varying(15) NOT NULL, -- IP address of the peer
    port integer NOT NULL, -- port number of the peer
    last_seen timestamp NOT NULL, -- last time the peer was active
    PRIMARY KEY (peer_id)
)
CREATE TABLE trading_platform.logs (
    log_id character varying(64) NOT NULL,  -- unique identifier for the log entry
    user_id character varying(64), -- identifier of the user associated with the log entry
    action character varying(128) NOT NULL, -- action performed
    details text NOT NULL, -- details of the action
    logged_at timestamp NOT NULL, -- time when the log entry was created
    PRIMARY KEY (log_id)
)


[User] Can you help me get the total number of operational platforms across all stations?

[Assistant] db.platforms.countDocuments({ status: 'Operational' });

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
// db.createCollection('platforms')
// Optional: db.platforms.createIndex({ platform_id: 1 }, { unique: true })
// Optional: db.platforms.createIndex({ station_id: 1 })
{
  _id: ObjectId(),
  platform_id: "plat_123", // String (unique)
  station_id: "station_xyz", // String (references stations.station_id)
  platform_number: "1A", // String
  track_number: "T1", // String
  status: "Operational", // String ('Operational', 'Maintenance', 'Closed')
  length_meters: 250.50, // Decimal128 or Double
  accessible: true // Boolean
}
// db.createCollection('routes')
// Optional: db.routes.createIndex({ route_id: 1 }, { unique: true })
{
  _id: ObjectId(),
  route_id: "route_ne_corr", // String (unique)
  route_name: "Northeast Corridor", // String
  description: "High-speed rail linking Boston and Washington D.C.", // String
  origin_station_id: "station_bos", // String (references stations.station_id)
  destination_station_id: "station_was", // String (references stations.station_id)
  is_active: true // Boolean
}
// db.createCollection('route_stations')
// Optional: db.route_stations.createIndex({ route_station_id: 1 }, { unique: true })
// Optional: db.route_stations.createIndex({ route_id: 1, sequence_order: 1 }, { unique: true })
{
  _id: ObjectId(),
  route_station_id: "rs_ne_1", // String (unique)
  route_id: "route_ne_corr", // String (references routes.route_id)
  station_id: "station_bos", // String (references stations.station_id)
  sequence_order: 1, // Int32
  distance_from_previous_km: null, // Decimal128 or Double (null for first stop)
  typical_stop_duration_minutes: null // Int32 (null for origin/destination or if no stop)
}
// --- OR --- Embed within the Route document:
// {
//   _id: ObjectId(), route_id: "route_ne_corr", ...,
//   stations: [
//     { station_id: "station_bos", sequence_order: 1, distance_from_previous_km: null, typical_stop_duration_minutes: null },
//     { station_id: "station_pvd", sequence_order: 2, distance_from_previous_km: 70.5, typical_stop_duration_minutes: 5 },
//     ...
//   ]
// }
// db.createCollection('schedules')
// Optional: db.schedules.createIndex({ schedule_id: 1 }, { unique: true })
// Optional: db.schedules.createIndex({ route_id: 1, departure_datetime: 1 })
{
  _id: ObjectId(),
  schedule_id: "sched_1122", // String (unique)
  train_id: "train_789", // String (references trains.train_id)
  route_id: "route_ne_corr", // String (references routes.route_id)
  departure_datetime: ISODate("2024-05-10T08:00:00-04:00"), // Date (with timezone)
  arrival_datetime: ISODate("2024-05-10T15:30:00-04:00"), // Date (with timezone)
  status: "Scheduled", // String ('Scheduled', 'On Time', 'Delayed', 'Cancelled', 'Arrived')
  notes: "Track work expected near Philadelphia" // String
}
// db.createCollection('schedule_stops')
// Optional: db.schedule_stops.createIndex({ stop_id: 1 }, { unique: true })
// Optional: db.schedule_stops.createIndex({ schedule_id: 1, sequence_order: 1 }, { unique: true })
{
  _id: ObjectId(),
  stop_id: "stop_sched1122_1", // String (unique)
  schedule_id: "sched_1122", // String (references schedules.schedule_id)
  station_id: "station_bos", // String (references stations.station_id)
  platform_id: "plat_bos_3", // String (references platforms.platform_id, nullable)
  sequence_order: 1, // Int32
  scheduled_arrival_time: null, // Date
  scheduled_departure_time: ISODate("2024-05-10T08:00:00-04:00"), // Date
  actual_arrival_time: null, // Date
  actual_departure_time: ISODate("2024-05-10T08:01:00-04:00"), // Date
  status: "On Time" // String
}
// --- OR --- Embed within the Schedule document using an array 'stops'
// db.createCollection('passengers')
// Optional: db.passengers.createIndex({ passenger_id: 1 }, { unique: true })
// Optional: db.passengers.createIndex({ email: 1 }, { unique: true, sparse: true })
// Optional: db.passengers.createIndex({ phone_number: 1 }, { unique: true, sparse: true })
{
  _id: ObjectId(),
  passenger_id: "pass_pqr", // String (unique)
  first_name: "Alice", // String
  last_name: "Smith", // String
  email: "alice.smith@example.com", // String (unique, sparse)
  phone_number: "+15551234567", // String (unique, sparse)
  date_of_birth: ISODate("1990-03-20"), // Date
  loyalty_program_id: "LOYALTY123", // String
  created_at: ISODate("2023-02-01T11:00:00Z") // Date
}
// db.createCollection('staff')
// Optional: db.staff.createIndex({ staff_id: 1 }, { unique: true })
// Optional: db.staff.createIndex({ employee_number: 1 }, { unique: true })
// Optional: db.staff.createIndex({ contact_email: 1 }, { unique: true, sparse: true })
{
  _id: ObjectId(),
  staff_id: "staff_mno", // String (unique)
  first_name: "Bob", // String
  last_name: "Jones", // String
  role: "Conductor", // String
  primary_station_id: null, // String (references stations.station_id, nullable)
  employee_number: "E12345", // String (unique)
  hire_date: ISODate("2018-06-01"), // Date
  contact_email: "bob.jones@example-rail.com", // String (unique, sparse)
  contact_phone: "+15559876543", // String
  is_active: true // Boolean
}


[User] Can you list the number of citizens registered each month in 2024? Please show the month and the citizen count.

[Assistant] SELECT TO_CHAR(registration_date, 'YYYY-MM') AS registration_month, COUNT(*) AS citizen_count FROM government_services.citizens WHERE registration_date >= '2024-01-01' AND registration_date < '2025-01-01' GROUP BY registration_month ORDER BY registration_month;

[User] Now, can you also show the number of verified citizens for each month?

[Assistant] SELECT TO_CHAR(registration_date, 'YYYY-MM') AS registration_month, COUNT(*) AS citizen_count, SUM(CASE WHEN is_verified = true THEN 1 ELSE 0 END) AS verified_citizen_count FROM government_services.citizens WHERE registration_date >= '2024-01-01' AND registration_date < '2025-01-01' GROUP BY registration_month ORDER BY registration_month;

[User] I see some months with zero verified citizens, but they still show up. Can you exclude months with zero verified citizens from the result?

[Assistant] SELECT registration_month, citizen_count, verified_citizen_count FROM (SELECT TO_CHAR(registration_date, 'YYYY-MM') AS registration_month, COUNT(*) AS citizen_count, SUM(CASE WHEN is_verified = true THEN 1 ELSE 0 END) AS verified_citizen_count FROM government_services.citizens WHERE registration_date >= '2024-01-01' AND registration_date < '2025-01-01' GROUP BY registration_month) sub WHERE verified_citizen_count > 0 ORDER BY registration_month;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE government_services.citizens ( citizen_id character varying(64) NOT NULL, national_id_number character varying(128) NOT NULL UNIQUE, first_name character varying(100) NOT NULL, last_name character varying(100) NOT NULL, date_of_birth date NOT NULL, gender character varying(20), primary_address text NOT NULL, contact_email character varying(128) UNIQUE, contact_phone character varying(32), registration_date timestamp NOT NULL, is_verified boolean DEFAULT false, PRIMARY KEY (citizen_id) )


[User] Can you show me the total number of passengers registered in the database?

[Assistant] db.passengers.countDocuments({})

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
// db.createCollection('passengers')
// Optional: db.passengers.createIndex({ passenger_id: 1 }, { unique: true })
// Optional: db.passengers.createIndex({ email: 1 }, { unique: true, sparse: true })
// Optional: db.passengers.createIndex({ phone_number: 1 }, { unique: true, sparse: true })
{
  _id: ObjectId(),
  passenger_id: "pass_pqr", // String (unique)
  first_name: "Alice", // String
  last_name: "Smith", // String
  email: "alice.smith@example.com", // String (unique, sparse)
  phone_number: "+15551234567", // String (unique, sparse)
  date_of_birth: ISODate("1990-03-20"), // Date
  loyalty_program_id: "LOYALTY123", // String
  created_at: ISODate("2023-02-01T11:00:00Z") // Date
}


[User] Can you help me count the total number of active staff members in the database?

[Assistant] db.staff.countDocuments({ is_active: true });

System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
// db.createCollection('stations')
// Optional: Add unique index: db.stations.createIndex({ station_id: 1 }, { unique: true })
{
  _id: ObjectId(), // Auto-generated MongoDB ID
  station_id: "station_xyz", // String (unique identifier, corresponds to SQL PK)
  station_name: "Grand Central Terminal", // String
  city: "New York", // String
  state_province: "NY", // String
  country_code: "USA", // String
  address: "89 E 42nd St, New York, NY 10017", // String
  timezone: "America/New_York", // String
  number_of_platforms: 44, // Int32
  created_at: ISODate("2023-01-15T10:00:00Z"), // Date
  last_updated_at: ISODate("2023-10-28T15:30:00Z") // Date
}
// db.createCollection('trains')
// Optional: db.trains.createIndex({ train_id: 1 }, { unique: true })
// Optional: db.trains.createIndex({ train_number: 1 }, { unique: true })
{
  _id: ObjectId(),
  train_id: "train_789", // String (unique)
  train_number: "Acela 2151", // String (unique)
  model: "Siemens Velaro", // String
  manufacturer: "Siemens", // String
  year_manufactured: 2010, // Int32
  capacity: 304, // Int32
  status: "Active", // String ('Active', 'Maintenance', 'Retired')
  last_maintenance_date: ISODate("2023-09-15"), // Date (Date part only relevant)
  next_maintenance_date: ISODate("2024-03-15") // Date (Date part only relevant)
}
// db.createCollection('bookings')
// Optional: db.bookings.createIndex({ booking_id: 1 }, { unique: true })
// Optional: db.bookings.createIndex({ passenger_id: 1 })
// Optional: db.bookings.createIndex({ schedule_id: 1 })
{
  _id: ObjectId(),
  booking_id: "book_zyx", // String (unique)
  passenger_id: "pass_pqr", // String (references passengers.passenger_id)
  schedule_id: "sched_1122", // String (references schedules.schedule_id)
  booking_datetime: ISODate("2024-04-15T14:30:00Z"), // Date
  status: "Confirmed", // String ('Confirmed', 'Cancelled', 'Pending')
  total_price: 150.75, // Decimal128 or Double
  currency_code: "USD", // String
  special_requests: "Wheelchair assistance required at origin" // String
}
// db.createCollection('staff')
// Optional: db.staff.createIndex({ staff_id: 1 }, { unique: true })
// Optional: db.staff.createIndex({ employee_number: 1 }, { unique: true })
// Optional: db.staff.createIndex({ contact_email: 1 }, { unique: true, sparse: true })
{
  _id: ObjectId(),
  staff_id: "staff_mno", // String (unique)
  first_name: "Bob", // String
  last_name: "Jones", // String
  role: "Conductor", // String
  primary_station_id: null, // String (references stations.station_id, nullable)
  employee_number: "E12345", // String (unique)
  hire_date: ISODate("2018-06-01"), // Date
  contact_email: "bob.jones@example-rail.com", // String (unique, sparse)
  contact_phone: "+15559876543", // String
  is_active: true // Boolean
}


[User] Show the total number of customers in each state.

[Assistant]
SELECT
  state,
  COUNT(customer_id)
FROM insurance.customers
GROUP BY
  state;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE insurance.customers ( customer_id text, first_name text, last_name text, date_of_birth date, ssn_hash text, address_line1 text, address_line2 text, city text, state text, zip_code text, country text, phone_number text, email text, created_at timestamp, updated_at timestamp, status text )
CREATE TABLE insurance.claims (
    claim_id character varying(64) NOT NULL, -- unique identifier for the claim
    policy_id character varying(64) NOT NULL, -- identifier of the policy under which the claim is made (FK to policies)
    customer_id character varying(64) NOT NULL, -- identifier of the customer making the claim (FK to customers)
    incident_date timestamp NOT NULL, -- date and time of the incident leading to the claim
    reported_date timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, -- date the claim was reported
    description text NOT NULL, -- detailed description of the incident and claim
    estimated_loss numeric(15, 2), -- initial estimated cost of the loss
    status character varying(30) NOT NULL, -- e.g., Filed, Processing, Under Review, Approved, Denied, Settled
    settlement_amount numeric(15, 2), -- final amount paid out
    settlement_date date,
    claim_handler_id character varying(64), -- identifier for the employee handling the claim (FK to employees/adjusters)
    police_report_number character varying(100),
    PRIMARY KEY (claim_id)
)
CREATE TABLE insurance.insurance_products (
    product_id character varying(64) NOT NULL, -- unique identifier for the insurance product
    product_name character varying(150) NOT NULL, -- name of the insurance product (e.g., 'Comprehensive Auto Insurance')
    product_type character varying(50) NOT NULL, -- category like 'Auto', 'Home', 'Life', 'Health', 'Travel'
    description text, -- detailed description of the product
    base_premium numeric(10, 2) NOT NULL, -- starting premium before adjustments
    coverage_details text, -- details about what is covered (could be JSON or structured text)
    underwriting_rules text, -- rules used for assessing risk and eligibility
    is_active boolean NOT NULL DEFAULT true, -- whether the product is currently offered
    created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
    updated_at timestamp,
    PRIMARY KEY (product_id)
)
CREATE TABLE insurance.claim_documents ( document_id character varying(64) NOT NULL, claim_id character varying(64) NOT NULL, document_type character varying(50) NOT NULL, file_name character varying(255) NOT NULL, file_path character varying(512) NOT NULL, file_size_bytes integer, mime_type character varying(100), uploaded_by character varying(64), uploaded_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, description text, PRIMARY KEY (document_id) )


[User] What are the training programs or certifications completed by a staff member with the role of Platform Supervisor?

[Assistant] I'm sorry, but I don't have access to information about the training programs or certifications completed by staff members. The data available to me only includes basic staff details such as name, role, and contact information. For details on training or certifications, please refer to the HR department or relevant training records.

System:
You are an SQL statement expert and you can refuse the user's question if the question is not related to the table structure. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE train_station_management.staff ( staff_id text PRIMARY KEY, first_name text, last_name text, role text, primary_station_id text, employee_number text UNIQUE, hire_date date, contact_email text UNIQUE, contact_phone text, is_active boolean )


[User] What are the fuel consumption rates per hour for the Boeing 747-8 model?

[Assistant] I'm sorry, but I can't provide information on the fuel consumption rates for the Boeing 747-8 model as this data is not included in the aircraft_models table. The table contains details such as model name, manufacturer, passenger capacity, and other specifications, but fuel consumption data is not available. If you have another question or need assistance with something else related to the table, I'm happy to help.

System:
You are an SQL statement expert and you can refuse the user's question if the question is not related to the table structure. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE manufacturing.aircraft_models ( model_id.text, model_name.text, manufacturer.text, passenger_capacity.integer, max_range_km.integer, engine_type.text, wingspan_m.numeric, status.text, first_flight_date.date )