[User] For each reservation, show me the guest's full name, the property name, and the room type name.

[Assistant]
SELECT r.reservation_id, g.first_name || ' ' || g.last_name AS guest_full_name, p.property_name, rt.type_name AS room_type_name
FROM hospitality_technology.reservations r
JOIN hospitality_technology.guests g ON r.guest_id = g.guest_id
JOIN hospitality_technology.properties p ON r.property_id = p.property_id
JOIN hospitality_technology.room_types rt ON r.room_type_id = rt.room_type_id;

[User] Can you only show those reservations where the number of children is at least 2, and order results by guest last name ascending?

[Assistant]
SELECT r.reservation_id, g.first_name || ' ' || g.last_name AS guest_full_name, p.property_name, rt.type_name AS room_type_name
FROM hospitality_technology.reservations r
JOIN hospitality_technology.guests g ON r.guest_id = g.guest_id
JOIN hospitality_technology.properties p ON r.property_id = p.property_id
JOIN hospitality_technology.room_types rt ON r.room_type_id = rt.room_type_id
WHERE r.num_children >= 2
ORDER BY g.last_name ASC;

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.room_types ( room_type_id text, property_id text, type_name text, description text, base_rate numeric, max_occupancy integer, bed_type text, area_sqft numeric, amenities text )
CREATE TABLE hospitality_technology.guests ( guest_id text, first_name text, last_name text, email text, phone_number text, date_of_birth date, address_line1 text, city text, state_province text, postal_code text, country_code text, preferences text, loyalty_member_id text, communication_consent boolean, created_at timestamp, updated_at timestamp )
CREATE TABLE hospitality_technology.reservations ( reservation_id text, property_id text, guest_id text, room_id text, room_type_id text, check_in_date date, check_out_date date, actual_check_in_ts timestamp, actual_check_out_ts timestamp, num_adults integer, num_children integer, status text, booking_source text, rate_plan_id text, total_amount numeric, amount_paid numeric, special_requests text, created_at timestamp, updated_at timestamp )


[User] List service orders placed in the last 7 days, showing order_id, service_name, guest full name, and order_timestamp.

[Assistant]
SELECT so.order_id, s.service_name, g.first_name || ' ' || g.last_name AS guest_name, so.order_timestamp
FROM hospitality_technology.service_orders so
JOIN hospitality_technology.services s ON so.service_id = s.service_id
JOIN hospitality_technology.guests g ON so.guest_id = g.guest_id
WHERE so.order_timestamp >= current_date - INTERVAL '7 days';

[User] Filter to only those orders with status 'Delivered' and sort by delivery_timestamp ascending.

[Assistant]
SELECT so.order_id, s.service_name, g.first_name || ' ' || g.last_name AS guest_name, so.order_timestamp, so.delivery_timestamp
FROM hospitality_technology.service_orders so
JOIN hospitality_technology.services s ON so.service_id = s.service_id
JOIN hospitality_technology.guests g ON so.guest_id = g.guest_id
WHERE so.order_timestamp >= current_date - INTERVAL '7 days'
  AND so.status = 'Delivered'
ORDER BY so.delivery_timestamp ASC;

[User] Also include the staff member who delivered the service as delivered_by (full name) and limit to 10 records.

[Assistant]
SELECT so.order_id, s.service_name, g.first_name || ' ' || g.last_name AS guest_name, so.order_timestamp, so.delivery_timestamp, st.first_name || ' ' || st.last_name AS delivered_by
FROM hospitality_technology.service_orders so
JOIN hospitality_technology.services s ON so.service_id = s.service_id
JOIN hospitality_technology.guests g ON so.guest_id = g.guest_id
JOIN hospitality_technology.staff st ON so.staff_id_delivered = st.staff_id
WHERE so.order_timestamp >= current_date - INTERVAL '7 days'
  AND so.status = 'Delivered'
ORDER BY so.delivery_timestamp ASC
LIMIT 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 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 )
CREATE TABLE hospitality_technology.guests ( guest_id.text, first_name.text, last_name.text, email.text, phone_number.text, date_of_birth.date, address_line1.text, city.text, state_province.text, postal_code.text, country_code.text, preferences.text, loyalty_member_id.text, communication_consent.boolean, created_at.timestamp, updated_at.timestamp )
CREATE TABLE hospitality_technology.reservations ( reservation_id.text, property_id.text, guest_id.text, room_id.text, room_type_id.text, check_in_date.date, check_out_date.date, actual_check_in_ts.timestamp, actual_check_out_ts.timestamp, num_adults.integer, num_children.integer, status.text, booking_source.text, rate_plan_id.text, total_amount.numeric, amount_paid.numeric, special_requests.text, created_at.timestamp, updated_at.timestamp )
CREATE TABLE hospitality_technology.staff ( staff_id.text, property_id.text, first_name.text, last_name.text, position.text, work_email.text, work_phone.text, hire_date.date, termination_date.date, is_active.boolean, access_level.integer, manager_id.text, created_at.timestamp )
CREATE TABLE hospitality_technology.services ( service_id.text, property_id.text, service_name.text, description.text, category.text, price.numeric, unit.text, is_available.boolean, department.text )
CREATE TABLE hospitality_technology.service_orders ( order_id.text, reservation_id.text, guest_id.text, service_id.text, staff_id_ordered.text, staff_id_delivered.text, order_timestamp.timestamp, delivery_timestamp.timestamp, quantity.integer, unit_price.numeric, total_price.numeric, status.text, notes.text, bill_id.text )
CREATE TABLE hospitality_technology.payments ( payment_id.text, reservation_id.text, guest_id.text, bill_id.text, amount.numeric, currency_code.text, payment_method.text, card_type.text, card_last_four.text, transaction_ref.text, payment_timestamp.timestamp, status.text, staff_id_processed.text, notes.text )
CREATE TABLE hospitality_technology.reviews ( review_id.text, property_id.text, reservation_id.text, guest_id.text, rating_overall.integer, rating_cleanliness.integer, rating_service.integer, rating_location.integer, rating_value.integer, comment.text, review_source.text, review_date.timestamp, is_public.boolean, staff_response.text, response_staff_id.text, response_date.timestamp )


[User] Find services that have associated documents with a 'Pending' verification status. Show the service name and the document type name.

[Assistant] SELECT DISTINCT s.service_name, dt.document_type_name FROM government_services.services AS s JOIN government_services.applications AS a ON s.service_id = a.service_id JOIN government_services.application_documents AS ad ON a.application_id = ad.application_id JOIN government_services.document_types AS dt ON ad.document_type_id = dt.document_type_id WHERE ad.verification_status = 'Pending';

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] For each user, show their username and how many unique conversations they have sent at least one message in where the conversation is a group chat.

[Assistant]
SELECT u.username, COUNT(DISTINCT m.conversation_id) AS group_chats_messaged_in
FROM social_media.users u
JOIN social_media.messages m ON u.user_id = m.sender_user_id
JOIN social_media.conversations c ON m.conversation_id = c.conversation_id
WHERE c.is_group_chat = TRUE
GROUP BY u.username;

[User] Instead, show only users who have sent messages in more than one group chat, and include their email addresses.

[Assistant]
SELECT u.username, u.email, COUNT(DISTINCT m.conversation_id) AS group_chats_messaged_in
FROM social_media.users u
JOIN social_media.messages m ON u.user_id = m.sender_user_id
JOIN social_media.conversations c ON m.conversation_id = c.conversation_id
WHERE c.is_group_chat = TRUE
GROUP BY u.username, u.email
HAVING COUNT(DISTINCT m.conversation_id) > 1;

[User] Also add the most recent message time sent by each user in these group chats.

[Assistant]
SELECT u.username, u.email, COUNT(DISTINCT m.conversation_id) AS group_chats_messaged_in, MAX(m.sent_at) AS last_message_time
FROM social_media.users u
JOIN social_media.messages m ON u.user_id = m.sender_user_id
JOIN social_media.conversations c ON m.conversation_id = c.conversation_id
WHERE c.is_group_chat = TRUE
GROUP BY u.username, u.email
HAVING COUNT(DISTINCT m.conversation_id) > 1;

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, username text, email text, password_hash text, full_name text, profile_picture_url text, bio text, location text, created_at timestamp, updated_at timestamp, is_verified boolean )
CREATE TABLE social_media.posts ( post_id.text, user_id.text, content.text, media_url.text, media_type.text, created_at.timestamp, updated_at.timestamp, visibility.text, location_lat.numeric, location_lon.numeric )
CREATE TABLE social_media.comments (
    comment_id character varying(64) NOT NULL, -- unique identifier for the comment
    post_id character varying(64) NOT NULL, -- identifier of the post being commented on (FK to posts.post_id)
    user_id character varying(64) NOT NULL, -- identifier of the user who made the comment (FK to users.user_id)
    parent_comment_id character varying(64), -- identifier of the parent comment if it's a reply (FK to comments.comment_id)
    content text NOT NULL, -- textual content of the comment
    created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, -- timestamp of comment creation
    updated_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, -- timestamp of last comment edit
    PRIMARY KEY (comment_id)
)
CREATE TABLE social_media.likes ( like_id text, user_id text, post_id text, comment_id text, created_at timestamp )
CREATE TABLE social_media.follows ( follow_id character varying(64) NOT NULL, follower_user_id character varying(64) NOT NULL, following_user_id character varying(64) NOT NULL, created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, PRIMARY KEY (follow_id), CONSTRAINT unique_follow UNIQUE (follower_user_id, following_user_id) )
CREATE TABLE social_media.hashtags ( hashtag_id character varying(64) NOT NULL, tag_name character varying(100) NOT NULL UNIQUE, created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, PRIMARY KEY (hashtag_id) )
CREATE TABLE social_media.post_hashtags ( post_hashtag_id character varying(64) NOT NULL, post_id character varying(64) NOT NULL, hashtag_id character varying(64) NOT NULL, PRIMARY KEY (post_hashtag_id), CONSTRAINT unique_post_hashtag UNIQUE (post_id, hashtag_id) )
CREATE TABLE social_media.messages (
    message_id character varying(64) NOT NULL, -- unique identifier for the message
    conversation_id character varying(64) NOT NULL, -- identifier for the conversation thread (FK to conversations.conversation_id)
    sender_user_id character varying(64) NOT NULL, -- identifier of the sender (FK to users.user_id)
    content text, -- textual content of the message
    media_url text, -- URL to attached media (image/video)
    media_type character varying(20), -- type of media ('image', 'video', null)
    sent_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, -- timestamp when message was sent
    read_at timestamp, -- timestamp when message was read by recipient(s)
    PRIMARY KEY (message_id)
)
CREATE TABLE social_media.conversations ( conversation_id text PRIMARY KEY, created_at timestamp, last_message_at timestamp, is_group_chat bool, group_name text )
CREATE TABLE social_media.conversation_participants (
    participant_id character varying(64) NOT NULL, -- unique identifier for the participant entry
    conversation_id character varying(64) NOT NULL, -- identifier of the conversation (FK to conversations.conversation_id)
    user_id character varying(64) NOT NULL, -- identifier of the user in the conversation (FK to users.user_id)
    joined_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, -- timestamp when user joined the conversation
    last_read_at timestamp, -- timestamp indicating up to when the user has read messages
    PRIMARY KEY (participant_id),
    CONSTRAINT unique_user_conversation UNIQUE (conversation_id, user_id) -- prevent user being added multiple times
)
CREATE TABLE social_media.notifications ( notification_id.text, recipient_user_id.text, sender_user_id.text, notification_type.text, target_entity_id.text, target_entity_type.text, created_at.timestamp, read_at.timestamp )


[User] List games that have servers deployed in more than one geographical region. Show the game title and the count of regions.

[Assistant] SELECT g.title, count(DISTINCT s.region) AS region_count FROM games AS g JOIN servers AS s ON g.game_id = s.game_id GROUP BY g.game_id, g.title HAVING count(DISTINCT s.region) > 1;

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 gaming_technology.games ( game_id uuid PRIMARY KEY, title text, developer_id uuid, publisher_id uuid, genre text, release_date date, description text, platform text, engine text, website text )
CREATE TABLE gaming_technology.game_sessions ( session_id uuid PRIMARY KEY, player_id uuid, game_id uuid, server_id uuid, start_time timestamptz, end_time timestamptz, duration_seconds int, score int, session_data jsonb )
CREATE TABLE gaming_technology.servers ( server_id.uuid, game_id.uuid, server_name.text, region.text, ip_address.text, port.integer, current_players.integer, max_players.integer, status.text, last_heartbeat.timestamptz )
CREATE TABLE gaming_technology.achievements ( achievement_id.uuid, game_id.uuid, name.text, description.text, icon_url.text, points.integer, hidden.boolean )
CREATE TABLE gaming_technology.player_achievements ( player_achievement_id uuid NOT NULL DEFAULT gen_random_uuid(), player_id uuid NOT NULL, achievement_id uuid NOT NULL, unlocked_at timestamp with time zone NOT NULL DEFAULT CURRENT_TIMESTAMP, PRIMARY KEY (player_achievement_id), UNIQUE (player_id, achievement_id) )
CREATE TABLE gaming_technology.in_game_items ( item_id uuid, game_id uuid, item_name text, item_type text, description text, rarity text, cost_currency text, cost_amount numeric, attributes jsonb )
CREATE TABLE gaming_technology.player_inventory ( inventory_id.uuid, player_id.uuid, item_id.uuid, quantity.integer, acquired_at.timestamptz, instance_data.jsonb )


[User] Find all pairs of contracts deployed by the same deployer on the same day, showing the deployer_address, the deployment date, and both contract IDs.

[Assistant]
SELECT c1.deployer_address,
       DATE(c1.deployed_at) AS deploy_date,
       c1.contract_id AS contract_id_1,
       c2.contract_id AS contract_id_2
FROM web3.contracts c1
JOIN web3.contracts c2
  ON c1.deployer_address = c2.deployer_address
 AND DATE(c1.deployed_at) = DATE(c2.deployed_at)
 AND c1.contract_id < c2.contract_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.contracts ( contract_id.text, address.text, abi.text, bytecode.text, deployer_address.text, deployed_at.timestamp, network_id.text, status.text )


[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] I need to identify pairs of verified documents submitted by the same citizen. For each pair, display the citizen_id, the earlier document_id with its verification timestamp, and the later document_id with its verification timestamp.

[Assistant]
SELECT
  d1.citizen_id,
  d1.document_id AS earlier_document_id,
  d1.verification_timestamp AS earlier_verification,
  d2.document_id AS later_document_id,
  d2.verification_timestamp AS later_verification
FROM government_services.documents d1
JOIN government_services.documents d2
  ON d1.citizen_id = d2.citizen_id
  AND d1.verification_timestamp < d2.verification_timestamp
WHERE d1.verification_status = 'Verified'
  AND d2.verification_status = 'Verified';

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) )


[User] Find all documents that are larger than 5MB. Show the document ID, claim ID, file name, and file size in bytes.

[Assistant]
SELECT document_id, claim_id, file_name, file_size_bytes
FROM insurance.claim_documents
WHERE file_size_bytes > 5242880;

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.claims ( claim_id character varying(64) NOT NULL, policy_id character varying(64) NOT NULL, customer_id character varying(64) NOT NULL, incident_date timestamp NOT NULL, reported_date timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, description text NOT NULL, estimated_loss numeric(15, 2), status character varying(30) NOT NULL, settlement_amount numeric(15, 2), settlement_date date, claim_handler_id character varying(64), police_report_number character varying(100), PRIMARY KEY (claim_id) )
CREATE TABLE insurance.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] Show me each patient's full name along with the name of every doctor they've had an appointment with.

[Assistant]
SELECT p.first_name || ' ' || p.last_name AS patient_full_name, d.first_name || ' ' || d.last_name AS doctor_full_name
FROM healthcare.appointments a
JOIN healthcare.patients p ON a.patient_id = p.patient_id
JOIN healthcare.doctors d ON a.doctor_id = d.doctor_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 healthcare.patients ( patient_id text PRIMARY KEY, first_name text, last_name text, date_of_birth date, gender text, address text, phone_number text, email text, emergency_contact_name text, emergency_contact_phone text, created_at timestamp, updated_at timestamp )
CREATE TABLE healthcare.doctors ( doctor_id text PRIMARY KEY, first_name text, last_name text, specialty text, license_number text, phone_number text, email text, hospital_affiliation_id text, created_at timestamp, updated_at timestamp )
CREATE TABLE healthcare.appointments ( appointment_id text PRIMARY KEY, patient_id text, doctor_id text, appointment_time timestamp, duration_minutes int, reason text, status text, location_id text, notes text, created_at timestamp )
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 text PRIMARY KEY, 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 int, prescription_date timestamp )
CREATE TABLE healthcare.patient_insurance ( patient_insurance_id text PRIMARY KEY, 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] For each user, list all pairs of read and unread notifications, showing the recipient_user_id, the unread notification_id and type, and the read notification_id and type.

[Assistant]
SELECT
  n_unread.recipient_user_id,
  n_unread.notification_id   AS unread_id,
  n_unread.notification_type AS unread_type,
  n_read.notification_id     AS read_id,
  n_read.notification_type   AS read_type
FROM social_media.notifications n_unread
JOIN social_media.notifications n_read
  ON n_unread.recipient_user_id = n_read.recipient_user_id
WHERE n_unread.read_at IS NULL
  AND n_read.read_at IS NOT NULL;

[User] Actually, only include pairs where the unread notification_type is 'message'.

[Assistant]
SELECT
  n_unread.recipient_user_id,
  n_unread.notification_id   AS unread_id,
  n_unread.notification_type AS unread_type,
  n_read.notification_id     AS read_id,
  n_read.notification_type   AS read_type
FROM social_media.notifications n_unread
JOIN social_media.notifications n_read
  ON n_unread.recipient_user_id = n_read.recipient_user_id
WHERE n_unread.read_at IS NULL
  AND n_read.read_at IS NOT NULL
  AND n_unread.notification_type = 'message';

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.notifications ( notification_id character varying(64) NOT NULL, recipient_user_id character varying(64) NOT NULL, sender_user_id character varying(64), notification_type character varying(30) NOT NULL, target_entity_id character varying(64), target_entity_type character varying(20), created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, read_at timestamp, PRIMARY KEY (notification_id) )


[User] List all claim documents where the file name contains 'invoice' (case insensitive), showing the document ID, claim ID, file name, and uploaded_at.

[Assistant]
SELECT document_id, claim_id, file_name, uploaded_at
FROM insurance.claim_documents
WHERE LOWER(file_name) LIKE '%invoice%';

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.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.claim_documents ( document_id text PRIMARY KEY, claim_id text, document_type text, file_name text, file_path text, file_size_bytes int, mime_type text, uploaded_by text, uploaded_at timestamp, description text )


[User] List the first name and last name of all policy beneficiaries, along with the name of the insurance product associated with their policy.

[Assistant] SELECT T1.first_name, T1.last_name, T2.product_name FROM insurance.policy_beneficiaries AS T1 JOIN insurance.insurance_products AS T2 ON T1.policy_id = T2.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.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.policy_beneficiaries ( beneficiary_id text PRIMARY KEY, policy_id text, customer_id text, first_name text, last_name text, relationship text, percentage_share numeric, contact_info text, added_at timestamp )


[User] List the names of services for which documents are set to expire in the next 90 days.

[Assistant] SELECT DISTINCT T1.service_name FROM government_services.services AS T1 JOIN applications AS T2 ON T1.service_id = T2.service_id JOIN government_services.documents AS T3 ON T2.application_id = T3.application_id WHERE T3.expiry_date IS NOT NULL AND T3.expiry_date BETWEEN CURRENT_DATE AND CURRENT_DATE + INTERVAL '90 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 government_services.services ( service_id text PRIMARY KEY, agency_id text, service_name text, description text, category text, eligibility_criteria text, standard_fee numeric, average_processing_time_days int, is_active boolean, online_application_url text )
CREATE TABLE government_services.documents ( document_id text PRIMARY KEY, application_id text, citizen_id text, document_type text, file_reference text, upload_timestamp timestamp, expiry_date date, verification_status text, verified_by_employee_id text, verification_timestamp timestamp )


[User] Could you list each game_id along with the count of hidden achievements and the count of visible achievements?

[Assistant]
SELECT game_id,
       SUM(CASE WHEN hidden THEN 1 ELSE 0 END) AS hidden_count,
       SUM(CASE WHEN NOT hidden THEN 1 ELSE 0 END) AS visible_count
FROM gaming_technology.achievements
GROUP BY game_id;

[User] Actually, please provide pairs of one hidden and one visible achievement name for each game where both types exist.

[Assistant]
SELECT h.game_id,
       h.name AS hidden_name,
       v.name AS visible_name
FROM gaming_technology.achievements h
JOIN gaming_technology.achievements v
  ON h.game_id = v.game_id
 AND h.hidden = TRUE
 AND v.hidden = FALSE
WHERE EXISTS (
  SELECT 1 FROM gaming_technology.achievements x
   WHERE x.game_id = h.game_id
     AND x.hidden = FALSE
)
AND EXISTS (
  SELECT 1 FROM gaming_technology.achievements y
   WHERE y.game_id = h.game_id
     AND y.hidden = TRUE
);

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 gaming_technology.achievements ( achievement_id.uuid, game_id.uuid, name.text, description.text, icon_url.text, points.integer, hidden.boolean )


[User] Show me the total number of trades and the sum of total_amount for each status in the trades table.

[Assistant]
SELECT
  t.status,
  COUNT(t.trade_id) AS trade_count,
  SUM(t.total_amount) AS total_amount_by_status
FROM financial_services.trades t
GROUP BY t.status;

[User] Now, only include statuses where trade_count is greater than 100, and restrict to trades executed in the last 30 days.

[Assistant]
SELECT
  t.status,
  COUNT(t.trade_id) AS trade_count,
  SUM(t.total_amount) AS total_amount_by_status
FROM financial_services.trades t
WHERE t.trade_timestamp >= CURRENT_DATE - INTERVAL '30 days'
GROUP BY t.status
HAVING COUNT(t.trade_id) > 100;

[User] Exclude any statuses where the sum of commission is null or less than 1000.

[Assistant]
SELECT
  t.status,
  COUNT(t.trade_id) AS trade_count,
  SUM(t.total_amount) AS total_amount_by_status,
  SUM(t.commission) AS total_commission
FROM financial_services.trades t
WHERE t.trade_timestamp >= CURRENT_DATE - INTERVAL '30 days'
GROUP BY t.status
HAVING COUNT(t.trade_id) > 100
   AND SUM(t.commission) >= 1000;

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.trades ( trade_id character varying(64) NOT NULL, account_id character varying(64) NOT NULL, security_id character varying(64) NOT NULL, order_id character varying(64), trade_type character varying(10) NOT NULL, quantity numeric(19, 8) NOT NULL, price_per_unit numeric(19, 8) NOT NULL, total_amount numeric(19, 4) NOT NULL, commission numeric(10, 4), trade_timestamp timestamp NOT NULL, settlement_date date, status character varying(32) NOT NULL, execution_venue character varying(100), PRIMARY KEY (trade_id), FOREIGN KEY (account_id) REFERENCES financial_services.accounts(account_id), FOREIGN KEY (security_id) REFERENCES financial_services.securities(security_id) )
CREATE TABLE financial_services.employees ( employee_id character varying(64) NOT NULL, first_name character varying(100) NOT NULL, last_name character varying(100) NOT NULL, job_title character varying(100) NOT NULL, department character varying(100), branch_id character varying(64), email character varying(128) NOT NULL UNIQUE, phone_extension character varying(20), hire_date date NOT NULL, termination_date date, manager_id character varying(64), status character varying(32) NOT NULL, PRIMARY KEY (employee_id), FOREIGN KEY (branch_id) REFERENCES financial_services.branches(branch_id), FOREIGN KEY (manager_id) REFERENCES financial_services.employees(employee_id) )


[User] Find the average percentage share among all beneficiaries for each distinct relationship type.

[Assistant] SELECT relationship, AVG(percentage_share) FROM insurance.policy_beneficiaries GROUP BY relationship ORDER BY relationship;


[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] List each transaction along with its status and the names of any events that were emitted during that transaction.

[Assistant]
SELECT tr.transaction_id, tr.status, e.event_name
FROM web3.transactions tr
LEFT JOIN web3.events e ON tr.transaction_id = e.transaction_id;

[User] Only show transactions that had more than one event emitted, and list the number of events for each such transaction.

[Assistant]
SELECT tr.transaction_id, tr.status, COUNT(e.event_id) AS event_count
FROM web3.transactions tr
JOIN web3.events e ON tr.transaction_id = e.transaction_id
GROUP BY tr.transaction_id, tr.status
HAVING COUNT(e.event_id) > 1;

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) )
CREATE TABLE web3.events ( event_id.text, contract_id.text, event_name.text, data.text, emitted_at.timestamp, transaction_id.text, log_index.integer )
CREATE TABLE web3.transactions ( transaction_id character varying(64) NOT NULL, from_address character varying(128) NOT NULL, to_address character varying(128), value numeric(38,14) NOT NULL, gas_used integer NOT NULL, gas_price numeric(38,14) NOT NULL, block_number integer NOT NULL, timestamp timestamp NOT NULL, input_data text, status character varying(32) NOT NULL, nonce integer NOT NULL, PRIMARY KEY (transaction_id) )
CREATE TABLE web3.tokens (
    token_id character varying(64) NOT NULL,  -- unique identifier for the token
    contract_address character varying(128) NOT NULL, -- address of the token contract
    token_name character varying(128) NOT NULL, -- name of the token
    token_symbol character varying(32) NOT NULL, -- symbol of the token
    decimals integer NOT NULL, -- number of decimals for the token
    total_supply numeric(38,14) NOT NULL, -- total supply of the token
    PRIMARY KEY (token_id)
)
CREATE TABLE web3.token_transfers ( transfer_id text PRIMARY KEY, token_id text, from_address text, to_address text, value numeric, transaction_id text, log_index int )
CREATE TABLE web3.wallets ( wallet_id text, user_id text, address text, private_key text, created_at timestamp )


[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] I need to know the total USD value of all ERC-20 holdings by each wallet. Calculate the sum of (amount * price) using the latest token prices from token_prices_latest, grouped by wallet_address.

[Assistant]
SELECT eb.wallet_address,
       SUM(CAST(eb.amount AS numeric) * tpl.price) AS total_usd_value
FROM erc20_balances eb
JOIN token_prices_latest tpl
  ON lower(eb.contract_address) = lower(tpl.address)
GROUP BY eb.wallet_address;

[User] Actually, only include tokens where the price is greater than 0.5 USD and limit to the top 10 wallets by total_usd_value.

[Assistant]
SELECT eb.wallet_address,
       SUM(CAST(eb.amount AS numeric) * tpl.price) AS total_usd_value
FROM erc20_balances eb
JOIN token_prices_latest tpl
  ON lower(eb.contract_address) = lower(tpl.address)
WHERE tpl.price > 0.5
GROUP BY eb.wallet_address
ORDER BY total_usd_value DESC
LIMIT 10;

[User] Also show me the count of distinct token contracts held by each wallet as distinct_tokens.

[Assistant]
SELECT eb.wallet_address,
       SUM(CAST(eb.amount AS numeric) * tpl.price) AS total_usd_value,
       COUNT(DISTINCT lower(eb.contract_address)) AS distinct_tokens
FROM erc20_balances eb
JOIN token_prices_latest tpl
  ON lower(eb.contract_address) = lower(tpl.address)
WHERE tpl.price > 0.5
GROUP BY eb.wallet_address
ORDER BY total_usd_value DESC
LIMIT 10;

[User] Finally, filter out wallets that hold fewer than 2 distinct tokens.

[Assistant]
SELECT eb.wallet_address,
       SUM(CAST(eb.amount AS numeric) * tpl.price) AS total_usd_value,
       COUNT(DISTINCT lower(eb.contract_address)) AS distinct_tokens
FROM erc20_balances eb
JOIN token_prices_latest tpl
  ON lower(eb.contract_address) = lower(tpl.address)
WHERE tpl.price > 0.5
GROUP BY eb.wallet_address
HAVING COUNT(DISTINCT lower(eb.contract_address)) >= 2
ORDER BY total_usd_value DESC
LIMIT 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 erc20_balances ( block_number.bigint, contract_address.text, wallet_address.text, amount.text, pk.text )
CREATE TABLE nft_holders (
    block_number bigint NOT NULL, -- Block number containing the transaction
    contract_address varchar NOT NULL, -- Event contract address
    wallet_address varchar NOT NULL, -- The wallet address for the contract(with bloom filter)
    token_id varchar NOT NULL, -- NFT token id
    contract_type varchar NOT NULL, -- NFT contract type
    amount varchar NOT NULL, -- Number of held NFTs
    pk varchar NOT NULL  -- The last string partition of the contract.
)
CREATE TABLE sui_nfts ( object_id varchar, status varchar, collection_type varchar, package_id varchar, previous_transaction varchar, display varchar, owner varchar, name varchar )
CREATE TABLE token_prices ( uuid varchar, blockchain varchar, address varchar, decimals bigint, symbol varchar, 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, block_timestamp timestamp, transaction_index integer, transaction_hash text, log_index integer, contract_address text, pk integer )
CREATE TABLE token_balances ( block_number bigint, block_timestamp timestamp, tick text, wallet_address text, total_supply decimal, amount decimal )
CREATE TABLE token_info (
    block_timestamp timestamp(3) NOT NULL, -- 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(3) NOT NULL, block_number bigint NOT NULL, tx_index integer NOT NULL, tx_hash varchar(66) NOT NULL, tick varchar(255) NOT NULL, max_supply decimal(38,0) NOT NULL, lim decimal(38,0) NOT NULL, wlim decimal(38,0) NOT NULL, dec integer NOT NULL, creator varchar(42) NOT NULL )
CREATE TABLE token_activities_avalanche ( block_timestamp timestamp(3) NOT NULL, block_number bigint NOT NULL, tx_index integer NOT NULL, tx_hash varchar(66) NOT NULL, log_index integer NOT NULL, type varchar(20) NOT NULL, tick varchar(255) NOT NULL, id varchar(255) NOT NULL, amt decimal(38,0) NOT NULL, from_address varchar(42) NOT NULL, to_address varchar(42) NOT NULL )
CREATE TABLE token_balances_avalanche ( block_number bigint, block_timestamp timestamp, tick text, wallet_address text, total_supply decimal, amount decimal )


[User] How many wallets has each user created since '2024-07-01'?

[Assistant]
SELECT user_id,
       COUNT(*) AS wallet_count
FROM trading_platform.wallets
WHERE created_at >= '2024-07-01'
GROUP BY user_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 trading_platform.wallets ( wallet_id text, user_id text, address text, private_key text, created_at timestamp )


[User] How many smart contracts were created in the year 2023?

[Assistant] SELECT COUNT(*) FROM blockchain.smart_contracts WHERE timestamp >= '2023-01-01' AND timestamp < '2024-01-01';

[User] List the top 5 creator addresses based on the total number of smart contracts they have deployed.

[Assistant] SELECT creator_address, COUNT(*) AS contract_count FROM blockchain.smart_contracts GROUP BY creator_address ORDER BY contract_count DESC LIMIT 5;

System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE blockchain.smart_contracts ( contract_id.text, creator_address.text, code.text, timestamp.timestamp )


[User] List the first name, last name, license number, and status for all drivers whose license expires in the next 6 months.

[Assistant]
SELECT
  first_name,
  last_name,
  license_number,
  status
FROM transportation.drivers
WHERE
  license_expiry_date BETWEEN CURRENT_DATE AND CURRENT_DATE + INTERVAL '6 month'
ORDER BY
  license_expiry_date;

[User] Now, count how many drivers from that list have an 'Active' status.

[Assistant]
SELECT
  COUNT(*)
FROM transportation.drivers
WHERE
  license_expiry_date BETWEEN CURRENT_DATE AND CURRENT_DATE + INTERVAL '6 month' AND status = 'Active';

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.drivers ( driver_id text PRIMARY KEY, employee_id text, first_name text, last_name text, license_number text, license_expiry_date date, contact_number text, email text, hire_date date, status text )


[User] Show me the total number of invoices issued.

[Assistant] SELECT COUNT(*) FROM invoices;

[User] How many invoices were issued in each status?

[Assistant] SELECT status, COUNT(*) FROM invoices GROUP BY status;

[User] Only include statuses that have more than 10 invoices.

[Assistant] SELECT status, COUNT(*) FROM invoices GROUP BY status HAVING COUNT(*) > 10;

[User] Also, only consider invoices issued in the year 2023 and order the results by the count in descending order.

[Assistant] SELECT status, COUNT(*) FROM invoices WHERE EXTRACT(YEAR FROM issue_date) = 2023 GROUP BY status HAVING COUNT(*) > 10 ORDER BY 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 legal_services.invoices ( invoice_id.text, invoice_number.text, client_id.text, case_id.text, issue_date.date, due_date.date, total_amount.numeric, amount_paid.numeric, status.text, payment_date.timestamp, notes.text, created_at.timestamp )


[User] Show me the wallet addresses holding the ERC20 token with contract address '0xabcdeffedcba9876543210abcdefedcba9876'. Include the amount they hold.

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

[User] Instead of contract address, can you do this for a token symbol like 'USDC'?

[Assistant] SELECT eb.wallet_address, eb.amount FROM erc20_balances eb JOIN token_metas tm ON eb.contract_address = tm.contract_address WHERE tm.symbol = 'USDC' AND tm.is_erc20 = 1;

[User] Filter the results to only show wallets holding more than 1000 of this token.

[Assistant] SELECT eb.wallet_address, eb.amount FROM erc20_balances eb JOIN token_metas tm ON eb.contract_address = tm.contract_address WHERE tm.symbol = 'USDC' AND tm.is_erc20 = 1 AND CAST(eb.amount AS DECIMAL) > 1000;

System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE token_metas ( block_timestamp timestamp, block_number bigint, transaction_hash text, transaction_index bigint, from_address text, contract_address text, symbol text, total_supply text, name text, decimals bigint, is_erc20 integer, is_erc721 integer, is_erc1155 integer, is_proxy integer, extra_info text, pk integer )
CREATE TABLE erc1155_approval_for_all ( block_number bigint, block_timestamp timestamp, transaction_index integer, transaction_hash text, log_index integer, contract_address text )
CREATE TABLE erc20_balances ( block_number bigint, contract_address text, wallet_address text, amount text, pk text )
CREATE TABLE erc20_balances_historical ( block_number bigint, contract_address text, wallet_address text, amount text, pk integer )
CREATE TABLE nft_holders ( block_number bigint, contract_address text, wallet_address text, token_id text, contract_type text, amount text, pk text )
CREATE TABLE sui_coins_metadata ( object_id text, coin_type text, status text, decimals bigint, description text, icon_url text, symbol text, name text )
CREATE TABLE sui_nfts ( object_id text, status text, collection_type text, package_id text, previous_transaction text, display text, owner text, name text )
CREATE TABLE nft_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 text, contract_address text, name text, symbol text, deploy_block_number bigint, deploy_block_time bigint, erc_type text, owner text, traits text, description text, slug text, media_info text, image_url text, banner_image_url text, updated_at bigint, banner text, token_count bigint, floor_price text, floor_price_symbol text, floor_price_contract text, pk integer )
CREATE TABLE token_prices_latest ( blockchain text, address text, decimals bigint, symbol text, price real, timestamp timestamp )
CREATE TABLE token_info ( 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 ( block_timestamp timestamp, block_number bigint, tx_index integer, tx_hash text, log_index integer, type text, tick text, id text, amt decimal, from_address text, to_address text )
CREATE TABLE mud_holesky_redstone ( address text, table_id text, key_bytes text, key0 text, key1 text, static_data text, encoded_lengths text, dynamic_data text, is_deleted boolean, block_number bigint, log_index bigint )
CREATE TABLE token_balances_bitcoin ( block_number bigint, block_timestamp timestamp, tick text, wallet_address text, total_supply text, amount text )
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_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 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 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] List all reviews with their property IDs and overall ratings where the rating is 4 or higher.

[Assistant] SELECT review_id, property_id, rating_overall FROM hospitality_technology.reviews WHERE rating_overall >= 4;

[User] Now, include only reviews that have a staff response.

[Assistant] SELECT review_id, property_id, rating_overall FROM hospitality_technology.reviews WHERE rating_overall >= 4 AND staff_response IS NOT NULL;

[User] The query is missing the review date. Can you include that as well?

[Assistant] SELECT review_id, property_id, rating_overall, review_date FROM hospitality_technology.reviews WHERE rating_overall >= 4 AND staff_response IS NOT NULL;

[User] Actually, I need to see the reviews ordered by rating in descending order, and only show the top 10.

[Assistant] SELECT review_id, property_id, rating_overall, review_date FROM hospitality_technology.reviews WHERE rating_overall >= 4 AND staff_response IS NOT NULL ORDER BY rating_overall DESC LIMIT 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 hospitality_technology.reservations ( reservation_id.text, property_id.text, guest_id.text, room_id.text, room_type_id.text, check_in_date.date, check_out_date.date, actual_check_in_ts.timestamp, actual_check_out_ts.timestamp, num_adults.integer, num_children.integer, status.text, booking_source.text, rate_plan_id.text, total_amount.numeric, amount_paid.numeric, special_requests.text, created_at.timestamp, updated_at.timestamp )
CREATE TABLE hospitality_technology.service_orders ( order_id character varying(64) NOT NULL, reservation_id character varying(64), guest_id character varying(64) NOT NULL, service_id character varying(64) NOT NULL, staff_id_ordered character varying(64), staff_id_delivered character varying(64), order_timestamp timestamp with time zone NOT NULL DEFAULT current_timestamp, delivery_timestamp timestamp with time zone, quantity integer NOT NULL DEFAULT 1, unit_price numeric(10, 2) NOT NULL, total_price numeric(12, 2) NOT NULL, status character varying(50) NOT NULL, notes text, bill_id character varying(64), PRIMARY KEY (order_id), FOREIGN KEY (reservation_id) REFERENCES hospitality_technology.reservations(reservation_id), FOREIGN KEY (guest_id) REFERENCES hospitality_technology.guests(guest_id), FOREIGN KEY (service_id) REFERENCES hospitality_technology.services(service_id), FOREIGN KEY (staff_id_ordered) REFERENCES hospitality_technology.staff(staff_id), FOREIGN KEY (staff_id_delivered) REFERENCES hospitality_technology.staff(staff_id) )
CREATE TABLE hospitality_technology.reviews ( review_id character varying(64) NOT NULL, property_id character varying(64) NOT NULL, reservation_id character varying(64) UNIQUE, guest_id character varying(64) NOT NULL, rating_overall integer, rating_cleanliness integer, rating_service integer, rating_location integer, rating_value integer, comment text, review_source character varying(100), review_date timestamp with time zone NOT NULL DEFAULT current_timestamp, is_public boolean DEFAULT true, staff_response text, response_staff_id character varying(64), response_date timestamp with time zone, PRIMARY KEY (review_id), FOREIGN KEY (property_id) REFERENCES hospitality_technology.properties(property_id), FOREIGN KEY (reservation_id) REFERENCES hospitality_technology.reservations(reservation_id), FOREIGN KEY (guest_id) REFERENCES hospitality_technology.guests(guest_id), FOREIGN KEY (response_staff_id) REFERENCES hospitality_technology.staff(staff_id) )


[User] How many likes were given to comments in June 2024?

[Assistant]
SELECT COUNT(*) AS comment_likes_count
FROM social_media.likes
WHERE comment_id IS NOT NULL
  AND DATE_TRUNC('month', created_at) = '2024-06-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.comments ( comment_id character varying(64) NOT NULL, post_id character varying(64) NOT NULL, user_id character varying(64) NOT NULL, parent_comment_id character varying(64), content text NOT NULL, created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, updated_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, PRIMARY KEY (comment_id) )
CREATE TABLE social_media.likes ( like_id character varying(64) NOT NULL, user_id character varying(64) NOT NULL, post_id character varying(64), comment_id character varying(64), created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, PRIMARY KEY (like_id), CONSTRAINT unique_user_like UNIQUE (user_id, post_id, comment_id), CONSTRAINT check_like_target CHECK (post_id IS NOT NULL OR comment_id IS NOT NULL) )
CREATE TABLE social_media.post_hashtags ( post_hashtag_id character varying(64) NOT NULL, post_id character varying(64) NOT NULL, hashtag_id character varying(64) NOT NULL, PRIMARY KEY (post_hashtag_id), CONSTRAINT unique_post_hashtag UNIQUE (post_id, hashtag_id) )
CREATE TABLE social_media.conversations ( conversation_id character varying(64) NOT NULL, created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, last_message_at timestamp, is_group_chat boolean NOT NULL DEFAULT false, group_name character varying(100), PRIMARY KEY (conversation_id) )
CREATE TABLE social_media.notifications ( notification_id character varying(64) NOT NULL, recipient_user_id character varying(64) NOT NULL, sender_user_id character varying(64), notification_type character varying(30) NOT NULL, target_entity_id character varying(64), target_entity_type character varying(20), created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, read_at timestamp, PRIMARY KEY (notification_id) )
CREATE TABLE social_media.user_settings ( setting_id character varying(64) NOT NULL, user_id character varying(64) NOT NULL UNIQUE, theme character varying(20) DEFAULT 'light', email_notifications_enabled boolean DEFAULT true, push_notifications_enabled boolean DEFAULT true, private_profile boolean DEFAULT false, updated_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, PRIMARY KEY (setting_id) )


[User] Show me the top 5 projects by valuation that completed fundraising rounds in the last 3 months, along with their narrative information if available.

[Assistant] SELECT pfr.project_name, pfr.valuation, pfr.rounds_name, pfr.investment_date, ni.narrative, ni.trend_rank FROM project_fundraising_record pfr LEFT JOIN token_basic_info tbi ON pfr.project_name = tbi.token_name LEFT JOIN narrative_info ni ON tbi.narrative = ni.narrative WHERE pfr.investment_date >= DATE_SUB(CURRENT_DATE, INTERVAL 3 MONTH) ORDER BY pfr.valuation DESC LIMIT 5;

[User] Can you also include the 24-hour trading volume for these projects' narratives and filter to only include projects with valuation over $50 million?

[Assistant] SELECT pfr.project_name, pfr.valuation, pfr.rounds_name, pfr.investment_date, ni.narrative, ni.trend_rank, ni.volume_24h FROM project_fundraising_record pfr LEFT JOIN token_basic_info tbi ON pfr.project_name = tbi.token_name LEFT JOIN narrative_info ni ON tbi.narrative = ni.narrative WHERE pfr.investment_date >= DATE_SUB(CURRENT_DATE, INTERVAL 3 MONTH) AND pfr.valuation > 50000000 ORDER BY pfr.valuation 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 project_fundraising_record ( id character varying(32) NOT NULL,  -- fundraising record id project_id character varying(32) NOT NULL, -- the invested project's id project_name character varying(128) NOT NULL, -- name of the invested project rounds_name character varying(32), -- name of the fundraising round investment_value numeric(38,14), -- amount of the fundraising in USD investment_date character varying(128), -- the date of the investment happened introduction character varying(128), -- the introduction of the invested project valuation numeric(38,14), -- the valuation of the project in USD when invested )
CREATE TABLE token_basic_info ( coin_id character varying(100) NOT NULL, token_name character varying(100) NOT NULL, token_symbol character varying(100) NOT NULL, token_address character varying(100) NOT NULL, chain text, price double precision, price_change_percentage_1h double precision, price_change_percentage_24h double precision, price_change_percentage_7d double precision, highest_price_24h double precision, lowest_price_24h double precision, market_cap double precision, market_cap_rank bigint, market_cap_change_percentage_24h text, total_volume text, narrative text, trend_rank bigint )
 "CREATE TABLE narrative_info (",
    "narrative character varying(512) NOT NULL, -- the id of narrative",
    "top_3_coins text, -- the top 3 tokens in the narrative",
    "price_change_percentage_1h double precision, -- change in value divided by the absolute price value of the original token price in 1 hour in the narrative",
    "price_change_percentage_24h double precision, -- change in value divided by the absolute price value of the original token price in 24 hours in the narrative",
    "price_change_percentage_7d double precision, -- change in value divided by the absolute price value of the original token price in 7 days in the narrative",
    "market_cap double precision, -- the market cap of the narrative",
    "volume_24h double precision, -- the trade volume of the narrative",
    "trend_rank bigint, -- the trending rank of the narrative, value 1 expresses the most popular narrative",
    "token_num bigint, -- total token number in the narrative",
    ",PRIMARY KEY (narrative));"

CREATE TABLE cex_token_balance ( snapshot_time character varying(32) NOT NULL, chain character varying(128) NOT NULL, address character varying(128) NOT NULL, exchange character varying(512) NOT NULL, token_address character varying(128) NOT NULL, token_symbol character varying(512), balance numeric(38,10), usd_value numeric(38,14), price double precision )
CREATE TABLE smart_money_profit ( address character varying(100) NOT NULL, rank INT, profit numeric(38,6), roi numeric(38,2), realized_ratio numeric(38,2), most_profit_token character varying(100), last_trade_time character varying(100), chain character varying(100) )
CREATE TABLE smart_money_token_performance ( token_address character varying(100) NOT NULL, token_symbol character varying(100), pnl numeric(38,2), net_flow numeric(38,2), avg_cost numeric(38,16), price double precision, realized_ratio numeric(10,2), roi numeric(10,2), chain character varying(100) )


[User] List all appointments scheduled in the next 30 days with appointment_id, client_id, case_id, and any invoice_id linked to that case.

[Assistant]
SELECT
  a.appointment_id,
  a.client_id,
  a.case_id,
  i.invoice_id
FROM legal_services.appointments AS a
LEFT JOIN legal_services.invoices AS i
  ON a.case_id = i.case_id
WHERE a.start_time BETWEEN CURRENT_DATE AND CURRENT_DATE + INTERVAL '30 days';

[User] Change to include only appointments with status 'Scheduled' and invoices that are not fully paid.

[Assistant]
SELECT
  a.appointment_id,
  a.client_id,
  a.case_id,
  i.invoice_id
FROM legal_services.appointments AS a
LEFT JOIN legal_services.invoices AS i
  ON a.case_id = i.case_id
WHERE a.start_time BETWEEN CURRENT_DATE AND CURRENT_DATE + INTERVAL '30 days'
  AND a.status = 'Scheduled'
  AND (i.status IS NULL OR i.status <> 'Paid');

[User] Also include only those where the case_type is 'Corporate'.

[Assistant]
SELECT
  a.appointment_id,
  a.client_id,
  a.case_id,
  i.invoice_id
FROM legal_services.appointments AS a
JOIN legal_services.cases AS c
  ON a.case_id = c.case_id
LEFT JOIN legal_services.invoices AS i
  ON a.case_id = i.case_id
WHERE a.start_time BETWEEN CURRENT_DATE AND CURRENT_DATE + INTERVAL '30 days'
  AND a.status = 'Scheduled'
  AND (i.status IS NULL OR i.status <> 'Paid')
  AND c.case_type = 'Corporate';

[User] Finally, order by start_time ascending and return only the first 10 rows.

[Assistant]
SELECT
  a.appointment_id,
  a.client_id,
  a.case_id,
  i.invoice_id
FROM legal_services.appointments AS a
JOIN legal_services.cases AS c
  ON a.case_id = c.case_id
LEFT JOIN legal_services.invoices AS i
  ON a.case_id = i.case_id
WHERE a.start_time BETWEEN CURRENT_DATE AND CURRENT_DATE + INTERVAL '30 days'
  AND a.status = 'Scheduled'
  AND (i.status IS NULL OR i.status <> 'Paid')
  AND c.case_type = 'Corporate'
ORDER BY a.start_time ASC
LIMIT 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 legal_services.law_firms (
    firm_id character varying(64) NOT NULL,  -- unique identifier for the law firm
    firm_name character varying(200) NOT NULL, -- official name of the law firm
    address text NOT NULL, -- primary address of the firm
    phone character varying(32), -- firm's main phone number
    website character varying(255), -- firm's website URL
    founded_date date, -- date the firm was established
    managing_partner_id character varying(64), -- FK to lawyers table (optional)
    PRIMARY KEY (firm_id)
)
CREATE TABLE legal_services.cases (
    case_id character varying(64) NOT NULL,  -- unique identifier for the case/matter
    case_number character varying(100) UNIQUE, -- official case number (court or internal)
    case_name text NOT NULL, -- descriptive name or title for the case
    client_id character varying(64) NOT NULL, -- FK to clients table
    lead_lawyer_id character varying(64) NOT NULL, -- FK to lawyers table (primary lawyer responsible)
    case_type character varying(100) NOT NULL, -- e.g., Litigation, Corporate, Family Law, IP
    status character varying(50) NOT NULL, -- e.g., Open, Closed, Pending, On Hold, Appealed
    date_opened timestamp NOT NULL, -- date the case was formally opened
    date_closed timestamp, -- date the case was closed (nullable)
    description text, -- detailed description of the case
    court_jurisdiction character varying(128), -- court or jurisdiction if applicable
    PRIMARY KEY (case_id)
)
CREATE TABLE legal_services.time_entries (
    entry_id character varying(64) NOT NULL,  -- unique identifier for the time entry
    case_id character varying(64) NOT NULL, -- FK to cases table
    lawyer_id character varying(64) NOT NULL, -- FK to lawyers table (who performed the work)
    date_worked date NOT NULL, -- date the work was performed
    hours_spent numeric(5, 2) NOT NULL CHECK (hours_spent > 0), -- duration of work in hours (e.g., 1.5 for 1h 30m)
    billing_rate numeric(10, 2) NOT NULL, -- hourly rate applied for this entry
    description text NOT NULL, -- detailed description of the work performed
    is_billable boolean DEFAULT true, -- whether this time entry is billable to the client
    is_billed boolean DEFAULT false, -- whether this entry has been included in an invoice
    invoice_id character varying(64), -- FK to invoices table (once billed)
    created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, -- when the entry was recorded
    PRIMARY KEY (entry_id)
)
CREATE TABLE legal_services.invoices (
    invoice_id character varying(64) NOT NULL,  -- unique identifier for the invoice
    invoice_number character varying(100) UNIQUE NOT NULL, -- user-facing invoice number
    client_id character varying(64) NOT NULL, -- FK to clients table
    case_id character varying(64), -- FK to cases table (optional, could be general retainer)
    issue_date date NOT NULL, -- date the invoice was generated
    due_date date NOT NULL, -- date the payment is due
    total_amount numeric(12, 2) NOT NULL, -- total amount due on the invoice
    amount_paid numeric(12, 2) DEFAULT 0.00, -- amount already paid
    status character varying(50) NOT NULL, -- e.g., Draft, Sent, Paid, Partially Paid, Overdue, Void
    payment_date timestamp, -- date the invoice was fully paid (nullable)
    notes text, -- additional notes or terms on the invoice
    created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
    PRIMARY KEY (invoice_id)
)
CREATE TABLE legal_services.appointments (
    appointment_id character varying(64) NOT NULL, -- unique identifier for the appointment
    client_id character varying(64) NOT NULL, -- FK to clients table
    lawyer_id character varying(64) NOT NULL, -- FK to lawyers table
    case_id character varying(64), -- FK to cases table (optional, if related to a specific case)
    start_time timestamp NOT NULL, -- scheduled start date and time
    end_time timestamp NOT NULL, -- scheduled end date and time
    location text, -- location of the meeting (address or virtual link)
    subject character varying(255), -- subject or purpose of the appointment
    notes text, -- additional notes for the appointment
    status character varying(50) NOT NULL, -- e.g., Scheduled, Completed, Canceled, Rescheduled
    created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
    PRIMARY KEY (appointment_id)
)


[User] For each asset, calculate the total quantity and average price of orders that have status 'filled'.

[Assistant]
SELECT o.asset_id,
       SUM(o.quantity) AS total_quantity,
       AVG(o.price)     AS average_price
FROM trading_platform.orders o
WHERE o.status = 'filled'
GROUP BY o.asset_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 trading_platform.wallets (
    wallet_id character varying(64) NOT NULL,  -- unique identifier for the wallet
    user_id character varying(64) NOT NULL, -- identifier of the user owning the wallet
    address character varying(128) NOT NULL, -- address of the wallet
    private_key text NOT NULL, -- private key of the wallet
    created_at timestamp NOT NULL, -- time when the wallet was created
    PRIMARY KEY (wallet_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.assets (
    asset_id character varying(64) NOT NULL,  -- unique identifier for the asset
    name character varying(128) NOT NULL, -- name of the asset
    symbol character varying(32) NOT NULL, -- symbol of the asset
    type character varying(32) NOT NULL, -- type of the asset (e.g., cryptocurrency, stock)
    PRIMARY KEY (asset_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.metadata (
    metadata_id character varying(64) NOT NULL,  -- unique identifier for the metadata
    asset_id character varying(64) NOT NULL, -- identifier of the asset the metadata is associated with
    key character varying(128) NOT NULL, -- key of the metadata
    value text NOT NULL, -- value of the metadata
    PRIMARY KEY (metadata_id)
)
CREATE TABLE trading_platform.kyc_audit (
    kyc_audit_id character varying(64) NOT NULL,  -- unique identifier for the KYC audit
    user_id character varying(64) NOT NULL, -- identifier of the user being audited
    status character varying(32) NOT NULL, -- status of the KYC audit (e.g., pending, approved, rejected)
    reviewed_at timestamp NOT NULL, -- time when the KYC audit was reviewed
    PRIMARY KEY (kyc_audit_id)
)
CREATE TABLE trading_platform.notifications (
    notification_id character varying(64) NOT NULL,  -- unique identifier for the notification
    user_id character varying(64) NOT NULL, -- identifier of the user receiving the notification
    message text NOT NULL, -- message of the notification
    sent_at timestamp NOT NULL, -- time when the notification was sent
    read_at timestamp, -- time when the notification was read
    PRIMARY KEY (notification_id)
)


[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 the top 5 projects by valuation that completed fundraising rounds in the last 12 months, along with their token symbol and price from the token_basic_info table.

[Assistant] SELECT pfr.project_name, pfr.valuation, tbi.token_symbol, tbi.price FROM project_fundraising_record pfr LEFT JOIN token_basic_info tbi ON pfr.project_name = tbi.token_name WHERE pfr.investment_date >= DATE_SUB(CURRENT_DATE, INTERVAL 12 MONTH) ORDER BY pfr.valuation DESC LIMIT 5;

[User] Can you also include the 24-hour trading volume for these projects' tokens and filter to only include projects with valuation over $100 million?

[Assistant] SELECT pfr.project_name, pfr.valuation, tbi.token_symbol, tbi.price, tbi.total_volume FROM project_fundraising_record pfr LEFT JOIN token_basic_info tbi ON pfr.project_name = tbi.token_name WHERE pfr.investment_date >= DATE_SUB(CURRENT_DATE, INTERVAL 12 MONTH) AND pfr.valuation > 100000000 ORDER BY pfr.valuation 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 project_fundraising_record (",
    "id character varying(32) NOT NULL,  -- fundraising record id",
    "project_id character varying(32) NOT NULL, -- the invested project's id",
    "project_name character varying(128) NOT NULL, -- name of the invested project",
    "rounds_name character varying(32), -- name of the fundraising round",
    "investment_value numeric(38,14), -- amount of the fundraising in USD",
    "investment_date character varying(128), -- the date of the investment happened",
    "introduction character varying(128), -- the introduction of the invested project",
    "valuation numeric(38,14), -- the valuation of the project in USD when invested",

CREATE TABLE token_basic_info ( coin_id character varying(100) NOT NULL, -- the id of the token token_name character varying(100) NOT NULL, -- the token's name token_symbol character varying(100) NOT NULL, -- the token's symbol token_address character varying(100) NOT NULL, -- the token's address chain text, -- the chain that the token resides price double precision, -- the current price of the token price_change_percentage_1h double precision, -- change in value divided by the absolute price value of the original token price in 1 hour price_change_percentage_24h double precision, -- change in value divided by the absolute price value of the original token price in 24 hours price_change_percentage_7d double precision, -- change in value divided by the absolute price value of the original token price in 7 days highest_price_24h double precision, -- the highest price of the token in 24 hours lowest_price_24h double precision,  -- the lowest price of the token in 24 hours market_cap double precision, -- the market cap of the token market_cap_rank bigint, -- the rank of the token market cap in desc market_cap_change_percentage_24h text, -- the percentage of market cap changes in 24 hours total_volume text, -- the trade volum of the token both in decentralized exchange(DEX) and centralized exchange(CEX) narrative text, -- the category or narrative of the token trend_rank biging, -- the trending rank of the token, value 1 expresses the most popular token. ,PRIMARY KEY (coin_id, chain) )
CREATE TABLE narrative_info ( narrative character varying(512) NOT NULL, -- the id of narrative top_3_coins text, -- the top 3 tokens in the narrative price_change_percentage_1h double precision, -- change in value divided by the absolute price value of the original token price in 1 hour in the narrative price_change_percentage_24h double precision, -- change in value divided by the absolute price value of the original token price in 24 hours in the narrative price_change_percentage_7d double precision, -- change in value divided by the absolute price value of the original token price in 7 days in the narrative market_cap double precision, -- the market cap of the narrative volume_24h double precision, -- the trade volume of the narrative trend_rank bigint, -- the trending rank of the narrative, value 1 expresses the most popular narrative token_num bigint, -- total token number in the narrative ,PRIMARY KEY (narrative) )
CREATE TABLE token_dexpool_info ( pair_address character varying(512) NOT NULL, token_name character varying(100) NOT NULL, token_symbol character varying(100) NOT NULL, chain text, price double precision, price_change_percentage_1h double precision, price_change_percentage_6h double precision, price_change_percentage_24h double precision, makers_24h double precision, volume_24h double precision, liquidity double precision, market_cap double precision, trend_rank bigint )
CREATE TABLE smart_money_profit ( address character varying(100) NOT NULL, rank INT, profit numeric(38,6), roi numeric(38,2), realized_ratio numeric(38,2), most_profit_token character varying(100), last_trade_time character varying(100), chain character varying(100) )
  "CREATE TABLE smart_money_token_performance (",
    "token_address character varying(100) NOT NULL, -- the token's address",
    "token_symbol character varying(100), -- the tokens's symbol",
    "pnl numeric(38,2), -- the profit users made on this token",
    "net_flow numeric(38,2), -- the netflow of the token, means the money user spent minus the the money user sold of this token",
    "avg_cost numeric(38,16), -- the average cost price of user spent on this token",
    "price double precision, -- the current price of the token",
    "realized_ratio numeric(10,2), -- the ratio user sold of the token",
    "roi numeric(10,2), -- the roi users made of this token",
    "chain character varying(100), -- the chain that the token resides",
    "PRIMARY KEY (token_address, chain));",

  "CREATE TABLE smart_money_token_inflow (",
    "token_address character varying(100) NOT NULL, -- the token's address",
    "token_symbol character varying(100), -- the tokens's symbol",
    "token_amount numeric(38,2), -- the absolute value of the amount if user bought minus  the amount user sold of this token",
    "usd_value numeric(38,2), -- the absolute usd value of the bought token minus sold token",
    "avg_price numeric(38,6), -- the average cost price of user spent on this token",
    "type int, -- the direction of the trade on this token. 1 means buying, 2 means selling",
    "address_amount integer, -- the amount of the user bought this token",
    "narrative character varying(100), -- the category or narrative of the token",
    "chain character varying(100), -- the chain that the token resides",
    ",PRIMARY KEY (token_address, chain)",


[User] For each recipient address, count how many token transfers they have received.

[Assistant] SELECT to_address, COUNT(*) AS received_transfer_count FROM web3.token_transfers GROUP BY to_address;

[User] Only show addresses that have received more than 100 transfers.

[Assistant] SELECT to_address, COUNT(*) AS received_transfer_count FROM web3.token_transfers GROUP BY to_address HAVING COUNT(*) > 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 web3.token_transfers ( transfer_id text PRIMARY KEY, token_id text, from_address text, to_address text, value numeric, transaction_id text, log_index int )