[User] Show a list of all trips along with the first and last names of all passengers who have booked on those trips. Each result should have the trip_id, passenger first name and last name.

[Assistant]
SELECT t.trip_id, p.first_name, p.last_name
FROM transportation.trips t
JOIN transportation.bookings b ON t.trip_id = b.trip_id
JOIN transportation.passengers p ON b.passenger_id = p.passenger_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 transportation.trips ( trip_id text PRIMARY KEY, route_id text, vehicle_id text, driver_id text, scheduled_departure timestamp, actual_departure timestamp, scheduled_arrival timestamp, actual_arrival timestamp, origin_location_id text, destination_location_id text, status text, passenger_count int, cargo_manifest_id text )
CREATE TABLE transportation.passengers (
    passenger_id character varying(64) NOT NULL,  -- unique identifier for the passenger
    first_name character varying(128) NOT NULL, -- passenger's first name
    last_name character varying(128) NOT NULL, -- passenger's last name
    email character varying(128) UNIQUE, -- email address
    phone_number character varying(32) UNIQUE, -- phone number
    date_of_birth date, -- passenger's date of birth
    loyalty_program_id character varying(64), -- identifier for loyalty program membership
    created_at timestamp with time zone NOT NULL, -- time when the passenger record was created
    PRIMARY KEY (passenger_id)
)


[User] List all pairs of drivers whose license_expiry_date falls in the same month and year. Display the first and last names of both drivers as driver1_first, driver1_last, driver2_first, driver2_last, and the shared year and month as expiry_year and expiry_month.

[Assistant]
SELECT d1.first_name AS driver1_first, d1.last_name AS driver1_last,
       d2.first_name AS driver2_first, d2.last_name AS driver2_last,
       EXTRACT(YEAR FROM d1.license_expiry_date) AS expiry_year,
       EXTRACT(MONTH FROM d1.license_expiry_date) AS expiry_month
FROM transportation.drivers d1
JOIN transportation.drivers d2
  ON EXTRACT(YEAR FROM d1.license_expiry_date) = EXTRACT(YEAR FROM d2.license_expiry_date)
 AND EXTRACT(MONTH FROM d1.license_expiry_date) = EXTRACT(MONTH FROM d2.license_expiry_date)
 AND d1.driver_id < d2.driver_id;

[User] Now limit to only those expiry dates in the year 2024.

[Assistant]
SELECT d1.first_name AS driver1_first, d1.last_name AS driver1_last,
       d2.first_name AS driver2_first, d2.last_name AS driver2_last,
       EXTRACT(YEAR FROM d1.license_expiry_date) AS expiry_year,
       EXTRACT(MONTH FROM d1.license_expiry_date) AS expiry_month
FROM transportation.drivers d1
JOIN transportation.drivers d2
  ON EXTRACT(YEAR FROM d1.license_expiry_date) = EXTRACT(YEAR FROM d2.license_expiry_date)
 AND EXTRACT(MONTH FROM d1.license_expiry_date) = EXTRACT(MONTH FROM d2.license_expiry_date)
 AND d1.driver_id < d2.driver_id
WHERE EXTRACT(YEAR FROM d1.license_expiry_date) = 2024;

[User] Also include only pairs where both drivers have status 'Active'.

[Assistant]
SELECT d1.first_name AS driver1_first, d1.last_name AS driver1_last,
       d2.first_name AS driver2_first, d2.last_name AS driver2_last,
       EXTRACT(YEAR FROM d1.license_expiry_date) AS expiry_year,
       EXTRACT(MONTH FROM d1.license_expiry_date) AS expiry_month
FROM transportation.drivers d1
JOIN transportation.drivers d2
  ON EXTRACT(YEAR FROM d1.license_expiry_date) = EXTRACT(YEAR FROM d2.license_expiry_date)
 AND EXTRACT(MONTH FROM d1.license_expiry_date) = EXTRACT(MONTH FROM d2.license_expiry_date)
 AND d1.driver_id < d2.driver_id
WHERE EXTRACT(YEAR FROM d1.license_expiry_date) = 2024
  AND d1.status = 'Active'
  AND d2.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] List each wallet with its corresponding user_id and the total number of notifications that user has received.

[Assistant]
SELECT w.wallet_id, w.user_id, COUNT(n.notification_id) as total_notifications
FROM trading_platform.wallets w
LEFT JOIN trading_platform.notifications n ON w.user_id = n.user_id
GROUP BY w.wallet_id, w.user_id;

[User] Can you also display only wallets for users who have received at least 5 notifications?

[Assistant]
SELECT w.wallet_id, w.user_id, COUNT(n.notification_id) as total_notifications
FROM trading_platform.wallets w
LEFT JOIN trading_platform.notifications n ON w.user_id = n.user_id
GROUP BY w.wallet_id, w.user_id
HAVING COUNT(n.notification_id) >= 5;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE trading_platform.wallets ( wallet_id.text, user_id.text, address.text, private_key.text, created_at.timestamp )
CREATE TABLE trading_platform.utxos ( utxo_id.text, transaction_id.text, output_index.integer, address.text, amount.numeric, spent.boolean )
CREATE TABLE trading_platform.peers ( peer_id.text, ip_address.text, port.integer, last_seen.timestamp )
CREATE TABLE trading_platform.metadata ( metadata_id.text, asset_id.text, key.text, value.text )
CREATE TABLE trading_platform.kyc_audit ( kyc_audit_id.text, user_id.text, status.text, reviewed_at.timestamp )
CREATE TABLE trading_platform.notifications ( notification_id.text, user_id.text, message.text, sent_at.timestamp, read_at.timestamp )


[User] For each game, show the game title, the total duration of all sessions in seconds, and the average score.

[Assistant] SELECT g.title, SUM(gs.duration_seconds) AS total_duration_seconds, AVG(gs.score) AS average_score FROM gaming_technology.games g JOIN gaming_technology.game_sessions gs ON g.game_id = gs.game_id GROUP BY g.game_id, g.title;

[User] Could you also show the total number of sessions for each game?

[Assistant] SELECT g.title, COUNT(gs.session_id) AS total_sessions, SUM(gs.duration_seconds) AS total_duration_seconds, AVG(gs.score) AS average_score FROM gaming_technology.games g JOIN gaming_technology.game_sessions gs ON g.game_id = gs.game_id GROUP BY g.game_id, g.title;

[User] Filter the results to only include games with more than 100 sessions.

[Assistant] SELECT g.title, COUNT(gs.session_id) AS total_sessions, SUM(gs.duration_seconds) AS total_duration_seconds, AVG(gs.score) AS average_score FROM gaming_technology.games g JOIN gaming_technology.game_sessions gs ON g.game_id = gs.game_id GROUP BY g.game_id, g.title HAVING COUNT(gs.session_id) > 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 gaming_technology.games ( game_id.uuid, title.text, developer_id.uuid, publisher_id.uuid, genre.text, release_date.date, description.text, platform.text, engine.text, website.text )
CREATE TABLE gaming_technology.developers ( developer_id uuid PRIMARY KEY, name text, country text, founded_year int, website text, created_at timestamptz )
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.achievements (
    achievement_id uuid NOT NULL DEFAULT gen_random_uuid(), -- unique identifier for an achievement definition
    game_id uuid NOT NULL, -- FK linking to the game the achievement belongs to
    name character varying(150) NOT NULL, -- name of the achievement
    description text NOT NULL, -- how to unlock the achievement
    icon_url character varying(255), -- URL for the achievement's icon
    points integer DEFAULT 0, -- points awarded for unlocking (optional)
    hidden boolean DEFAULT false, -- whether the achievement details are hidden until unlocked
    PRIMARY KEY (achievement_id)
    -- FOREIGN KEY (game_id) REFERENCES gaming_technology.games(game_id)
)
CREATE TABLE gaming_technology.player_inventory (
    inventory_id uuid NOT NULL DEFAULT gen_random_uuid(), -- unique identifier for an inventory entry
    player_id uuid NOT NULL, -- FK linking to the player owning the item
    item_id uuid NOT NULL, -- FK linking to the item definition
    quantity integer NOT NULL DEFAULT 1, -- number of items held (for stackable items)
    acquired_at timestamp with time zone NOT NULL DEFAULT CURRENT_TIMESTAMP, -- when the item was acquired
    instance_data jsonb, -- data specific to this instance (e.g., weapon mods, durability)
    PRIMARY KEY (inventory_id),
    -- Optional unique constraint if items are non-stackable or unique instances
    -- UNIQUE (player_id, item_id) -- Use if quantity is always 1
    -- FOREIGN KEY (player_id) REFERENCES gaming_technology.players(player_id),
    -- FOREIGN KEY (item_id) REFERENCES gaming_technology.in_game_items(item_id)
)


[User] List all applications that have at least one document with a verification status of 'Verified'. Show the application reference number and the name of the service associated with the application.

[Assistant]
SELECT
  T1.reference_number,
  T2.service_name
FROM government_services.applications AS T1
INNER JOIN government_services.services AS T2
  ON T1.service_id = T2.service_id
WHERE EXISTS (
  SELECT
    1
  FROM government_services.documents AS T3
  WHERE
    T3.application_id = T1.application_id AND T3.verification_status = 'Verified'
);

[User] Now, only include applications that were submitted in the year 2024.

[Assistant]
SELECT
  T1.reference_number,
  T2.service_name
FROM government_services.applications AS T1
INNER JOIN government_services.services AS T2
  ON T1.service_id = T2.service_id
WHERE EXISTS (
  SELECT
    1
  FROM government_services.documents AS T3
  WHERE
    T3.application_id = T1.application_id AND T3.verification_status = 'Verified'
)
AND EXTRACT(YEAR FROM T1.submitted_at) = 2024;

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)
)
CREATE TABLE government_services.agencies (
    agency_id character varying(64) NOT NULL, -- unique identifier for the agency
    agency_name character varying(255) NOT NULL, -- full name of the government agency
    jurisdiction_level character varying(50) NOT NULL, -- e.g., Federal, State, County, City
    primary_contact_email character varying(128),
    main_phone_number character varying(32),
    website_url character varying(255),
    established_date date,
    parent_agency_id character varying(64), -- FK to self for hierarchical structure
    PRIMARY KEY (agency_id)
)
CREATE TABLE government_services.services (
    service_id character varying(64) NOT NULL, -- unique identifier for the service
    agency_id character varying(64) NOT NULL, -- FK to agencies table
    service_name character varying(255) NOT NULL, -- name of the service (e.g., Driver's License Renewal)
    description text,
    category character varying(100), -- e.g., Licensing, Benefits, Taxation, Permits
    eligibility_criteria text, -- description of who is eligible
    standard_fee numeric(10, 2) DEFAULT 0.00, -- typical fee for the service
    average_processing_time_days integer, -- estimated processing time
    is_active boolean DEFAULT true, -- whether the service is currently offered
    online_application_url character varying(255),
    PRIMARY KEY (service_id)
)
CREATE TABLE government_services.documents (
    document_id character varying(64) NOT NULL, -- unique identifier for the document instance
    application_id character varying(64), -- FK to applications table (optional, could be linked to citizen directly)
    citizen_id character varying(64) NOT NULL, -- FK to citizens table
    document_type character varying(100) NOT NULL, -- e.g., Passport Scan, Proof of Address, Birth Certificate
    file_reference text NOT NULL, -- reference to the stored file (e.g., S3 URL, internal path)
    upload_timestamp timestamp NOT NULL,
    expiry_date date,
    verification_status character varying(30) DEFAULT 'Pending', -- e.g., Pending, Verified, Rejected
    verified_by_employee_id character varying(64), -- FK to employees table
    verification_timestamp timestamp,
    PRIMARY KEY (document_id)
)
CREATE TABLE government_services.appointments (
    appointment_id character varying(64) NOT NULL, -- unique identifier for the appointment
    citizen_id character varying(64) NOT NULL, -- FK to citizens table
    employee_id character varying(64), -- FK to employees table (optional, if assigned)
    location_id character varying(64), -- FK to service_locations table (if physical)
    service_id character varying(64), -- FK to services table (optional, if related to specific service)
    scheduled_start_time timestamp NOT NULL,
    scheduled_end_time timestamp,
    purpose text NOT NULL, -- reason for the appointment
    status character varying(30) NOT NULL, -- e.g., Scheduled, Completed, Cancelled, No-Show
    booking_method character varying(50), -- e.g., Online, Phone, In-Person
    created_at timestamp NOT NULL, -- when the appointment was booked
    notes text,
    PRIMARY KEY (appointment_id)
)
CREATE TABLE government_services.notifications (
    notification_id character varying(64) NOT NULL, -- unique identifier for the notification
    citizen_id character varying(64) NOT NULL, -- FK to citizens table
    application_id character varying(64), -- FK to applications table (optional)
    message_subject character varying(255),
    message_body text NOT NULL,
    channel character varying(30) NOT NULL, -- e.g., Email, SMS, Portal Message, Mail
    sent_at timestamp NOT NULL,
    status character varying(30) NOT NULL, -- e.g., Queued, Sent, Delivered, Failed, Read
    related_entity_type character varying(50), -- e.g., Application, Appointment, Document Request
    related_entity_id character varying(64), -- ID of the related entity
    PRIMARY KEY (notification_id)
)


[User] Show me all claims with police reports that were filed in the last 3 months, along with the policy details and customer information.

[Assistant] SELECT c.claim_id, c.policy_id, c.customer_id, c.incident_date, c.reported_date, c.description, c.estimated_loss, c.status, c.settlement_amount, c.settlement_date, c.police_report_number, p.product_id, p.product_name, p.product_type, b.first_name, b.last_name, b.relationship FROM insurance.claims c JOIN insurance.insurance_products p ON c.policy_id = p.product_id JOIN insurance.policy_beneficiaries b ON c.customer_id = b.customer_id WHERE c.police_report_number IS NOT NULL AND c.reported_date >= CURRENT_DATE - INTERVAL '3 months';

[User] Now filter to only show claims where the estimated loss is above $10,000.

[Assistant] SELECT c.claim_id, c.policy_id, c.customer_id, c.incident_date, c.reported_date, c.description, c.estimated_loss, c.status, c.settlement_amount, c.settlement_date, c.police_report_number, p.product_id, p.product_name, p.product_type, b.first_name, b.last_name, b.relationship FROM insurance.claims c JOIN insurance.insurance_products p ON c.policy_id = p.product_id JOIN insurance.policy_beneficiaries b ON c.customer_id = b.customer_id WHERE c.police_report_number IS NOT NULL AND c.reported_date >= CURRENT_DATE - INTERVAL '3 months' AND c.estimated_loss > 10000;

[User] I also want to see the count of such claims per product type.

[Assistant] SELECT p.product_type, COUNT(c.claim_id) AS claim_count FROM insurance.claims c JOIN insurance.insurance_products p ON c.policy_id = p.product_id WHERE c.police_report_number IS NOT NULL AND c.reported_date >= CURRENT_DATE - INTERVAL '3 months' AND c.estimated_loss > 10000 GROUP BY p.product_type;

[User] Finally, show me the average estimated loss for these claims by product type.

[Assistant] SELECT p.product_type, AVG(c.estimated_loss) AS avg_estimated_loss FROM insurance.claims c JOIN insurance.insurance_products p ON c.policy_id = p.product_id WHERE c.police_report_number IS NOT NULL AND c.reported_date >= CURRENT_DATE - INTERVAL '3 months' AND c.estimated_loss > 10000 GROUP BY p.product_type;

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.insurance_products ( product_id character varying(64) NOT NULL, product_name character varying(150) NOT NULL, product_type character varying(50) NOT NULL, description text, base_premium numeric(10, 2) NOT NULL, coverage_details text, underwriting_rules text, is_active boolean NOT NULL DEFAULT true, created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, updated_at timestamp, PRIMARY KEY (product_id) )
CREATE TABLE insurance.policy_beneficiaries ( beneficiary_id character varying(64) NOT NULL, policy_id character varying(64) NOT NULL, customer_id character varying(64) NOT NULL, first_name character varying(100) NOT NULL, last_name character varying(100) NOT NULL, relationship character varying(50) NOT NULL, percentage_share numeric(5, 2) NOT NULL CHECK (percentage_share > 0 AND percentage_share <= 100), contact_info text, added_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, PRIMARY KEY (beneficiary_id), UNIQUE (policy_id, customer_id) )


[User] Show me all rooms that are currently available (status = 'available') and have a non-smoking policy, along with their room type details including base rate and max occupancy.

[Assistant] SELECT r.room_id, r.room_number, r.floor, rt.type_name, rt.base_rate, rt.max_occupancy, rt.bed_type, rt.area_sqft FROM hospitality_technology.rooms r JOIN hospitality_technology.room_types rt ON r.room_type_id = rt.room_type_id WHERE r.status = 'available' AND r.is_smoking = false;

[User] Now, filter these results to only include rooms with a max occupancy of at least 4 people and order them by base rate in ascending order.

[Assistant] SELECT r.room_id, r.room_number, r.floor, rt.type_name, rt.base_rate, rt.max_occupancy, rt.bed_type, rt.area_sqft FROM hospitality_technology.rooms r JOIN hospitality_technology.room_types rt ON r.room_type_id = rt.room_type_id WHERE r.status = 'available' AND r.is_smoking = false AND rt.max_occupancy >= 4 ORDER BY rt.base_rate 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.rooms ( room_id character varying(64) NOT NULL, property_id character varying(64) NOT NULL, room_number character varying(10) NOT NULL, room_type_id character varying(64) NOT NULL, floor integer, status character varying(50) NOT NULL, is_smoking boolean NOT NULL DEFAULT false, features text, current_condition text, last_cleaned_at timestamp with time zone, PRIMARY KEY (room_id), FOREIGN KEY (property_id) REFERENCES hospitality_technology.properties(property_id), FOREIGN KEY (room_type_id) REFERENCES hospitality_technology.room_types(room_type_id) )
CREATE TABLE hospitality_technology.room_types ( room_type_id character varying(64) NOT NULL, property_id character varying(64) NOT NULL, type_name character varying(100) NOT NULL, description text, base_rate numeric(10, 2) NOT NULL, max_occupancy integer NOT NULL, bed_type character varying(50), area_sqft numeric(8,2), amenities text, PRIMARY KEY (room_type_id), FOREIGN KEY (property_id) REFERENCES hospitality_technology.properties(property_id) )
CREATE TABLE hospitality_technology.reservations ( reservation_id character varying(64) NOT NULL, property_id character varying(64) NOT NULL, guest_id character varying(64) NOT NULL, room_id character varying(64), room_type_id character varying(64) NOT NULL, check_in_date date NOT NULL, check_out_date date NOT NULL, actual_check_in_ts timestamp with time zone, actual_check_out_ts timestamp with time zone, num_adults integer NOT NULL, num_children integer DEFAULT 0, status character varying(50) NOT NULL, booking_source character varying(100), rate_plan_id character varying(64), total_amount numeric(12, 2), amount_paid numeric(12, 2) DEFAULT 0.00, special_requests text, created_at timestamp with time zone NOT NULL DEFAULT current_timestamp, updated_at timestamp with time zone NOT NULL DEFAULT current_timestamp, PRIMARY KEY (reservation_id), FOREIGN KEY (property_id) REFERENCES hospitality_technology.properties(property_id), FOREIGN KEY (guest_id) REFERENCES hospitality_technology.guests(guest_id), FOREIGN KEY (room_id) REFERENCES hospitality_technology.rooms(room_id), FOREIGN KEY (room_type_id) REFERENCES hospitality_technology.room_types(room_type_id) )
CREATE TABLE hospitality_technology.staff ( staff_id character varying(64) NOT NULL, property_id character varying(64) NOT NULL, first_name character varying(100) NOT NULL, last_name character varying(100) NOT NULL, position character varying(100) NOT NULL, work_email character varying(255) UNIQUE, work_phone character varying(30), hire_date date NOT NULL, termination_date date, is_active boolean NOT NULL DEFAULT true, access_level integer NOT NULL, manager_id character varying(64), created_at timestamp with time zone NOT NULL DEFAULT current_timestamp, PRIMARY KEY (staff_id), FOREIGN KEY (property_id) REFERENCES hospitality_technology.properties(property_id), FOREIGN KEY (manager_id) REFERENCES hospitality_technology.staff(staff_id) )


[User] Count the number of prescriptions each doctor has written for medications manufactured by 'Pfizer' in the last 6 months.

[Assistant]
SELECT p.doctor_id, COUNT(*) AS prescription_count
FROM healthcare.prescriptions p
JOIN healthcare.medications m ON p.medication_id = m.medication_id
WHERE m.manufacturer = 'Pfizer'
  AND p.prescription_date >= CURRENT_DATE - INTERVAL '6 months'
GROUP BY p.doctor_id;

[User] Actually, please include the doctor's full name instead of the ID, and order the results by prescription_count descending.

[Assistant]
SELECT p.doctor_id,
       d.first_name || ' ' || d.last_name AS doctor_name,
       COUNT(*) AS prescription_count
FROM healthcare.prescriptions p
JOIN healthcare.medications m ON p.medication_id = m.medication_id
JOIN healthcare.doctors d ON p.doctor_id = d.doctor_id
WHERE m.manufacturer = 'Pfizer'
  AND p.prescription_date >= CURRENT_DATE - INTERVAL '6 months'
GROUP BY p.doctor_id, doctor_name
ORDER BY prescription_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 healthcare.patients ( patient_id text, first_name text, last_name text, date_of_birth date, gender text, address text, phone_number text, email text, emergency_contact_name text, emergency_contact_phone text, created_at timestamp, updated_at timestamp )
CREATE TABLE healthcare.doctors ( doctor_id text, 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, patient_id.text, doctor_id.text, appointment_time.timestamp, duration_minutes.integer, reason.text, status.text, location_id.text, notes.text, created_at.timestamp )
CREATE TABLE healthcare.medications (
    medication_id character varying(64) NOT NULL, -- unique identifier for the medication type
    medication_name character varying(255) NOT NULL, -- common or brand name
    generic_name character varying(255), -- generic chemical name
    manufacturer character varying(100), -- drug manufacturer
    ndc_code character varying(20) UNIQUE, -- National Drug Code (optional but useful)
    description text, -- description of the medication
    PRIMARY KEY (medication_id)
)
CREATE TABLE healthcare.prescriptions ( prescription_id text, record_id text, patient_id text, doctor_id text, medication_id text, dosage text, frequency text, route text, start_date date, end_date date, quantity_dispensed numeric, refills_allowed integer, prescription_date timestamp )
CREATE TABLE healthcare.insurance_plans ( plan_id text, plan_name text, insurance_provider text, plan_type text, contact_phone text, website text )
CREATE TABLE healthcare.patient_insurance ( patient_insurance_id text, patient_id text, plan_id text, policy_number text, group_number text, subscriber_name text, effective_date date, expiration_date date, is_primary boolean )


[User] For each passenger, compute the count of bookings and average fare for bookings made in February 2024.

[Assistant]
SELECT p.passenger_id, COUNT(b.booking_id) AS booking_count, AVG(b.fare) AS avg_fare
FROM transportation.passengers p
JOIN transportation.bookings b ON p.passenger_id = b.passenger_id
WHERE b.booking_time >= '2024-02-01' AND b.booking_time < '2024-03-01'
GROUP BY p.passenger_id;

[User] I need to see the passengers' first and last names instead of IDs and only include those with an average fare greater than 75.

[Assistant]
SELECT p.first_name, p.last_name, COUNT(b.booking_id) AS booking_count, AVG(b.fare) AS avg_fare
FROM transportation.passengers p
JOIN transportation.bookings b ON p.passenger_id = b.passenger_id
WHERE b.booking_time >= '2024-02-01' AND b.booking_time < '2024-03-01'
GROUP BY p.first_name, p.last_name
HAVING AVG(b.fare) > 75;

[User] Also, order the results by booking_count descending and limit the output to the top 5 passengers.

[Assistant]
SELECT p.first_name, p.last_name, COUNT(b.booking_id) AS booking_count, AVG(b.fare) AS avg_fare
FROM transportation.passengers p
JOIN transportation.bookings b ON p.passenger_id = b.passenger_id
WHERE b.booking_time >= '2024-02-01' AND b.booking_time < '2024-03-01'
GROUP BY p.first_name, p.last_name
HAVING AVG(b.fare) > 75
ORDER BY booking_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 transportation.vehicles ( vehicle_id character varying(64) NOT NULL, license_plate character varying(32) NOT NULL UNIQUE, vin character varying(17) UNIQUE, make character varying(64) NOT NULL, model character varying(64) NOT NULL, year integer NOT NULL, type character varying(32) NOT NULL, capacity integer, fuel_type character varying(32) NOT NULL, status character varying(32) NOT NULL, depot_id character varying(64), acquisition_date date, PRIMARY KEY (vehicle_id) )
CREATE TABLE transportation.drivers ( driver_id text PRIMARY KEY, employee_id text, first_name text, last_name text, license_number text, license_expiry_date date, contact_number text, email text, hire_date date, status text )
CREATE TABLE transportation.passengers ( passenger_id.text, first_name.text, last_name.text, email.text, phone_number.text, date_of_birth.date, loyalty_program_id.text, created_at.timestamp )
CREATE TABLE transportation.bookings ( booking_id.text, passenger_id.text, trip_id.text, seat_number.text, booking_time.timestamp, status.text, fare.numeric, payment_transaction_id.text, special_requests.text )


[User] Could you list all games, show their title and genre, and also include the total number of achievements for each game?

[Assistant] SELECT g.title, g.genre, COUNT(a.achievement_id) AS total_achievements FROM gaming_technology.games g LEFT JOIN gaming_technology.achievements a ON g.game_id = a.game_id GROUP BY g.game_id, g.title, g.genre;

[User] Okay, now can you also include the developer's name for each game?

[Assistant] SELECT d.name AS developer_name, g.title, g.genre, COUNT(a.achievement_id) AS total_achievements FROM gaming_technology.games g JOIN gaming_technology.developers d ON g.developer_id = d.developer_id LEFT JOIN gaming_technology.achievements a ON g.game_id = a.game_id GROUP BY d.developer_id, d.name, g.game_id, g.title, g.genre;

[User] Can you filter the results to only show games from the 'Action' genre or games developed in 'Japan'?

[Assistant] SELECT d.name AS developer_name, g.title, g.genre, COUNT(a.achievement_id) AS total_achievements FROM gaming_technology.games g JOIN gaming_technology.developers d ON g.developer_id = d.developer_id LEFT JOIN gaming_technology.achievements a ON g.game_id = a.game_id WHERE g.genre = 'Action' OR d.country = 'Japan' GROUP BY d.developer_id, d.name, g.game_id, g.title, g.genre;

[User] Finally, order the results by the total number of achievements in descending order, and only show games with at least one achievement.

[Assistant] SELECT d.name AS developer_name, g.title, g.genre, COUNT(a.achievement_id) AS total_achievements FROM gaming_technology.games g JOIN gaming_technology.developers d ON g.developer_id = d.developer_id JOIN gaming_technology.achievements a ON g.game_id = a.game_id GROUP BY d.developer_id, d.name, g.game_id, g.title, g.genre HAVING COUNT(a.achievement_id) > 0 ORDER BY total_achievements DESC;


[User] Show projects that raised funds in 2023 along with their token symbols and current prices from token_basic_info.

[Assistant]
SELECT pfr.project_name,
       pfr.rounds_name,
       pfr.investment_value,
       tbi.token_symbol,
       tbi.price
FROM project_fundraising_record pfr
JOIN token_basic_info tbi
  ON pfr.project_name = tbi.token_name
WHERE pfr.investment_date LIKE '2023%';

[User] Include the 24h DEX trading volume for each token by joining with token_dexpool_info.

[Assistant]
SELECT pfr.project_name,
       pfr.rounds_name,
       pfr.investment_value,
       tbi.token_symbol,
       tbi.price,
       tdp.volume_24h
FROM project_fundraising_record pfr
JOIN token_basic_info tbi
  ON pfr.project_name = tbi.token_name
JOIN token_dexpool_info tdp
  ON tbi.token_symbol = tdp.token_symbol
     AND tbi.chain = tdp.chain
WHERE pfr.investment_date LIKE '2023%';

[User] Limit to projects with investment_value greater than 1000000.

[Assistant]
SELECT pfr.project_name,
       pfr.rounds_name,
       pfr.investment_value,
       tbi.token_symbol,
       tbi.price,
       tdp.volume_24h
FROM project_fundraising_record pfr
JOIN token_basic_info tbi
  ON pfr.project_name = tbi.token_name
JOIN token_dexpool_info tdp
  ON tbi.token_symbol = tdp.token_symbol
     AND tbi.chain = tdp.chain
WHERE pfr.investment_date LIKE '2023%'
  AND pfr.investment_value > 1000000;

[User] Order the results by investment_value descending and show top 10.

[Assistant]
SELECT pfr.project_name,
       pfr.rounds_name,
       pfr.investment_value,
       tbi.token_symbol,
       tbi.price,
       tdp.volume_24h
FROM project_fundraising_record pfr
JOIN token_basic_info tbi
  ON pfr.project_name = tbi.token_name
JOIN token_dexpool_info tdp
  ON tbi.token_symbol = tdp.token_symbol
     AND tbi.chain = tdp.chain
WHERE pfr.investment_date LIKE '2023%'
  AND pfr.investment_value > 1000000
ORDER BY pfr.investment_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 project_fundraising_record ( id text, project_id text, project_name text, rounds_name text, investment_value numeric, investment_date text, introduction text, valuation numeric )
CREATE TABLE token_basic_info ( coin_id text, token_name text, token_symbol text, token_address text, chain text, price numeric, price_change_percentage_1h numeric, price_change_percentage_24h numeric, price_change_percentage_7d numeric, highest_price_24h numeric, lowest_price_24h numeric, market_cap numeric, market_cap_rank numeric, market_cap_change_percentage_24h text, total_volume text, narrative text, trend_rank numeric )
CREATE TABLE narrative_info ( narrative text, top_3_coins text, price_change_percentage_1h numeric, price_change_percentage_24h numeric, price_change_percentage_7d numeric, market_cap numeric, volume_24h numeric, trend_rank numeric, token_num numeric )
CREATE TABLE token_dexpool_info ( pair_address text, token_name text, token_symbol text, chain text, price numeric, price_change_percentage_1h numeric, price_change_percentage_6h numeric, price_change_percentage_24h numeric, makers_24h numeric, volume_24h numeric, liquidity numeric, market_cap numeric, trend_rank numeric )
CREATE TABLE smart_money_token_performance ( token_address text, token_symbol text, pnl numeric, net_flow numeric, avg_cost numeric, price numeric, realized_ratio numeric, roi numeric, chain text )


[User] For each customer, what is their total premium amount and total deductible across all their policies?

[Assistant] SELECT customer_id, SUM(premium_amount) AS total_premium, SUM(deductible) AS total_deductible FROM insurance.policies GROUP BY customer_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.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] Give me the total number of reservations and the sum of total_amount by month for the year 2023.

[Assistant]
SELECT DATE_TRUNC('month', check_in_date) AS month,
       COUNT(*)                         AS reservation_count,
       SUM(total_amount)               AS total_revenue
FROM hospitality_technology.reservations
WHERE EXTRACT(YEAR FROM check_in_date) = 2023
GROUP BY DATE_TRUNC('month', check_in_date)
ORDER BY month;

[User] Actually, I only want reservations with status 'CheckedOut' or 'Completed'.

[Assistant]
SELECT DATE_TRUNC('month', check_in_date) AS month,
       COUNT(*)                         AS reservation_count,
       SUM(total_amount)               AS total_revenue
FROM hospitality_technology.reservations
WHERE EXTRACT(YEAR FROM check_in_date) = 2023
  AND status IN ('CheckedOut', 'Completed')
GROUP BY DATE_TRUNC('month', check_in_date)
ORDER BY month;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE hospitality_technology.reservations ( reservation_id text PRIMARY KEY, property_id text, guest_id text, room_id text, room_type_id text, check_in_date date, check_out_date date, actual_check_in_ts timestamp, actual_check_out_ts timestamp, num_adults int, num_children int, status text, booking_source text, rate_plan_id text, total_amount numeric, amount_paid numeric, special_requests text, created_at timestamp, updated_at timestamp )


[User] Find projects from the project_fundraising_record table that have completed both a 'Seed' fundraising round and a 'Series A' fundraising round.

[Assistant] SELECT pf_seed.project_name FROM project_fundraising_record pf_seed JOIN project_fundraising_record pf_seriesa ON pf_seed.project_id = pf_seriesa.project_id WHERE pf_seed.rounds_name = 'Seed' AND pf_seriesa.rounds_name = 'Series A';

[User] For these projects that had both a 'Seed' and 'Series A' round, show the investment value for both rounds side by side.

[Assistant] SELECT pf_seed.project_name, pf_seed.investment_value AS seed_investment, pf_seriesa.investment_value AS seriesa_investment FROM project_fundraising_record pf_seed JOIN project_fundraising_record pf_seriesa ON pf_seed.project_id = pf_seriesa.project_id WHERE pf_seed.rounds_name = 'Seed' AND pf_seriesa.rounds_name = 'Series A';

[User] Filter the results to only include projects where the investment value in the 'Series A' round was greater than the investment value in the 'Seed' round.

[Assistant] SELECT pf_seed.project_name, pf_seed.investment_value AS seed_investment, pf_seriesa.investment_value AS seriesa_investment FROM project_fundraising_record pf_seed JOIN project_fundraising_record pf_seriesa ON pf_seed.project_id = pf_seriesa.project_id WHERE pf_seed.rounds_name = 'Seed' AND pf_seriesa.rounds_name = 'Series A' AND pf_seriesa.investment_value > pf_seed.investment_value;

[User] Order the results by the 'Series A' investment value in descending order and show the top 5 projects.

[Assistant] SELECT pf_seed.project_name, pf_seed.investment_value AS seed_investment, pf_seriesa.investment_value AS seriesa_investment FROM project_fundraising_record pf_seed JOIN project_fundraising_record pf_seriesa ON pf_seed.project_id = pf_seriesa.project_id WHERE pf_seed.rounds_name = 'Seed' AND pf_seriesa.rounds_name = 'Series A' AND pf_seriesa.investment_value > pf_seed.investment_value ORDER BY seriesa_investment 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 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 smart_money_profit ( address character varying(100) NOT NULL, -- the user's address rank INT, -- the rank of the address in trade performance, value 1 expresses the best address. profit numeric(38,6), -- the profit user made in a month roi numeric(38,2), -- the roi of the user in a month realized_ratio numeric(38,2), -- the percentage of the user's realized profit most_profit_token character varying(100), -- the token symbol of the user's most profitable trade last_trade_time character varying(100), -- the last trade time of the user chain character varying(100), -- the chain that the address resides PRIMARY KEY (address, chain) )


[User] For each blockchain (chain), find the token with the highest ROI in the smart_money_token_performance table, and include that token's narrative from smart_money_token_inflow, its net_flow, and avg_cost.

[Assistant] WITH ranked_tokens AS ( SELECT p.chain, p.token_symbol, p.token_address, p.roi, p.avg_cost, i.narrative, i.net_flow, ROW_NUMBER() OVER (PARTITION BY p.chain ORDER BY p.roi DESC) AS rn FROM smart_money_token_performance p LEFT JOIN smart_money_token_inflow i ON p.token_address = i.token_address AND p.chain = i.chain ) SELECT chain, token_symbol, roi, narrative, net_flow, avg_cost FROM ranked_tokens WHERE rn = 1;

[User] Please exclude any tokens where net_flow is negative or NULL from these results.

[Assistant] WITH ranked_tokens AS ( SELECT p.chain, p.token_symbol, p.token_address, p.roi, p.avg_cost, i.narrative, i.net_flow, ROW_NUMBER() OVER (PARTITION BY p.chain ORDER BY p.roi DESC) AS rn FROM smart_money_token_performance p JOIN smart_money_token_inflow i ON p.token_address = i.token_address AND p.chain = i.chain WHERE i.net_flow > 0 ) SELECT chain, token_symbol, roi, narrative, net_flow, avg_cost FROM ranked_tokens WHERE rn = 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 smart_money_token_performance ( token_address text, token_symbol text, pnl numeric, net_flow numeric, avg_cost numeric, price numeric, realized_ratio numeric, roi numeric, chain text )
  "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 booking, show the booking ID, the passenger ID, the trip ID, and indicate if a special request was made.

[Assistant]
SELECT booking_id, passenger_id, trip_id,
       CASE WHEN special_requests IS NOT NULL AND special_requests <> '' THEN 'Yes' ELSE 'No' END AS has_special_request
FROM transportation.bookings;

[User] Can you only include bookings with special requests?

[Assistant]
SELECT booking_id, passenger_id, trip_id, special_requests
FROM transportation.bookings
WHERE special_requests IS NOT NULL AND special_requests <> '';

[User] Add the booking time and sort the results by most recent booking.

[Assistant]
SELECT booking_id, passenger_id, trip_id, special_requests, booking_time
FROM transportation.bookings
WHERE special_requests IS NOT NULL AND special_requests <> ''
ORDER BY booking_time DESC;

[User] Please only show the top 5 most recent bookings with special requests.

[Assistant]
SELECT booking_id, passenger_id, trip_id, special_requests, booking_time
FROM transportation.bookings
WHERE special_requests IS NOT NULL AND special_requests <> ''
ORDER BY booking_time 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 transportation.bookings (
    booking_id character varying(64) NOT NULL,  -- unique identifier for the booking
    passenger_id character varying(64) NOT NULL, -- identifier of the passenger making the booking
    trip_id character varying(64) NOT NULL, -- identifier of the trip being booked
    seat_number character varying(16), -- assigned seat number (if applicable)
    booking_time timestamp with time zone NOT NULL, -- time when the booking was made
    status character varying(32) NOT NULL, -- e.g., Confirmed, Cancelled, Pending Payment
    fare numeric(10, 2) NOT NULL, -- price paid for the booking
    payment_transaction_id character varying(128), -- reference to the payment transaction
    special_requests text, -- any special requests from the passenger
    PRIMARY KEY (booking_id)
)


[User] What is the average price of tokens held by Binance exchange across all chains in the cex_token_balance table?

[Assistant] SELECT AVG(price) AS average_price FROM cex_token_balance WHERE exchange = 'Binance';

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 cex_token_balance (",
    "snapshot_time character varying(32) NOT NULL,  -- the snapshot time of record, converted from original timestamp",
    "chain character varying(128) NOT NULL, -- the chain that the token resides",
    "address character varying(128) NOT NULL, -- the address that holds the assets, owned by a CEX",
    "exchange character varying(512) NOT NULL, -- a centralized exchange name",
    "token_address character varying(128) NOT NULL, -- token contract address",
    "token_symbol character varying(512), --token symbol",
    "balance numeric(38,10), -- token balance",
    "usd_value numeric(38,14), -- value of the token held in USD",
    "price double precision, --price of the token in USD",
    ",PRIMARY KEY (snapshot_time, exchange, address, chain, token_address));"


[User] Find all pairs of different insurance records that share the same group_number, and show group_number, the patient_insurance_id of both records, and their corresponding patient_ids.

[Assistant]
SELECT a.group_number,
       a.patient_insurance_id AS pi_id1,
       a.patient_id            AS patient1_id,
       b.patient_insurance_id AS pi_id2,
       b.patient_id            AS patient2_id
FROM healthcare.patient_insurance a
JOIN healthcare.patient_insurance b
  ON a.group_number = b.group_number
 AND a.patient_insurance_id < b.patient_insurance_id
WHERE a.group_number IS NOT NULL;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE healthcare.patient_insurance ( patient_insurance_id text, patient_id text, plan_id text, policy_number text, group_number text, subscriber_name text, effective_date date, expiration_date date, is_primary boolean )


[User] Find all wallets that hold at least one NFT and also hold ERC-20 tokens.

[Assistant]
SELECT DISTINCT nh.wallet_address
FROM nft_holders nh
JOIN erc20_balances eb
  ON nh.wallet_address = eb.wallet_address;

[User] Now show the count of distinct NFTs and count of distinct ERC-20 token contracts held by each such wallet.

[Assistant]
SELECT nh.wallet_address,
       COUNT(DISTINCT nh.contract_address || '-' || nh.token_id) AS nft_count,
       COUNT(DISTINCT eb.contract_address) AS erc20_count
FROM nft_holders nh
JOIN erc20_balances eb
  ON nh.wallet_address = eb.wallet_address
GROUP BY nh.wallet_address;

[User] Finally, only include wallets where erc20_count > 1 and nft_count > 2, and order by erc20_count descending.

[Assistant]
SELECT nh.wallet_address,
       COUNT(DISTINCT nh.contract_address || '-' || nh.token_id) AS nft_count,
       COUNT(DISTINCT eb.contract_address) AS erc20_count
FROM nft_holders nh
JOIN erc20_balances eb
  ON nh.wallet_address = eb.wallet_address
GROUP BY nh.wallet_address
HAVING COUNT(DISTINCT eb.contract_address) > 1
   AND COUNT(DISTINCT nh.contract_address || '-' || nh.token_id) > 2
ORDER BY erc20_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 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] List all agents who have a commission rate above 0.1 and show their full names and agency names.

[Assistant] SELECT agent_id, first_name || ' ' || last_name AS full_name, agency_name, commission_rate FROM insurance.agents WHERE commission_rate > 0.1 AND status = 'active';

[User] Now include only agents who were hired in the last 5 years.

[Assistant] SELECT agent_id, first_name || ' ' || last_name AS full_name, agency_name, commission_rate FROM insurance.agents WHERE commission_rate > 0.1 AND status = 'active' AND hire_date >= CURRENT_DATE - INTERVAL '5 years';

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 )
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.agents ( agent_id text, first_name text, last_name text, agency_name text, license_number text, license_state text, contact_email text, contact_phone text, hire_date date, termination_date date, status text, commission_rate numeric, manager_id text )
CREATE TABLE insurance.policy_beneficiaries ( beneficiary_id text, policy_id text, customer_id text, first_name text, last_name text, relationship text, percentage_share numeric, contact_info text, added_at timestamp )


[User] Show me all 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 all wallet addresses that hold more than 3 different NFTs from any ERC1155 contract. For each wallet, list the contract address and the count of distinct token_ids.

[Assistant]
SELECT contract_address, wallet_address, COUNT(DISTINCT token_id) AS token_id_count
FROM nft_holders
WHERE contract_type = 'ERC1155'
GROUP BY contract_address, wallet_address
HAVING COUNT(DISTINCT token_id) > 3;

[User] Can you also tell me the total amount of NFTs held by each of these wallets for the contracts they qualify for?

[Assistant]
SELECT contract_address, wallet_address, COUNT(DISTINCT token_id) AS token_id_count, SUM(CAST(amount AS numeric)) AS total_amount
FROM nft_holders
WHERE contract_type = 'ERC1155'
GROUP BY contract_address, wallet_address
HAVING COUNT(DISTINCT token_id) > 3;

[User] Actually, only include results for contracts where the total number of NFTs held by all wallets is over 1000. Show the contract address in the output.

[Assistant]
WITH contract_totals AS (
  SELECT contract_address, SUM(CAST(amount AS numeric)) AS contract_total_amount
  FROM nft_holders
  WHERE contract_type = 'ERC1155'
  GROUP BY contract_address
  HAVING SUM(CAST(amount AS numeric)) > 1000
)
SELECT n.contract_address, n.wallet_address, COUNT(DISTINCT n.token_id) AS token_id_count, SUM(CAST(n.amount AS numeric)) AS total_amount
FROM nft_holders n
JOIN contract_totals c ON n.contract_address = c.contract_address
WHERE n.contract_type = 'ERC1155'
GROUP BY n.contract_address, n.wallet_address
HAVING COUNT(DISTINCT n.token_id) > 3;

[User] Also include the name of the NFT for each token_id if available from nft_metadata. Only show NFTs on the Ethereum blockchain.

[Assistant]
WITH contract_totals AS (
  SELECT contract_address, SUM(CAST(amount AS numeric)) AS contract_total_amount
  FROM nft_holders
  WHERE contract_type = 'ERC1155'
  GROUP BY contract_address
  HAVING SUM(CAST(amount AS numeric)) > 1000
),
wallet_tokens AS (
  SELECT n.contract_address, n.wallet_address, n.token_id, SUM(CAST(n.amount AS numeric)) AS amount
  FROM nft_holders n
  JOIN contract_totals c ON n.contract_address = c.contract_address
  WHERE n.contract_type = 'ERC1155'
  GROUP BY n.contract_address, n.wallet_address, n.token_id
)
SELECT w.contract_address, w.wallet_address, w.token_id, w.amount, m.name AS nft_name
FROM wallet_tokens w
LEFT JOIN nft_metadata m
  ON m.blockchain = 'Ethereum' AND m.contract_address = w.contract_address AND m.token_id = w.token_id
WHERE w.amount > 0;

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, 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 ( object_id text, status text, coin_type text, balance text, owner 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 token_prices ( uuid text, blockchain text, address text, decimals bigint, symbol text, price real, timestamp timestamp )
CREATE TABLE token_prices_latest ( blockchain text, address text, decimals bigint, symbol text, price real, timestamp timestamp )
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, block_number bigint, tx_index integer, tx_hash text, tick text, max_supply decimal, lim decimal, wlim decimal, dec integer, creator 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_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] For each employee who has verified documents, show their full name and the total number of documents they have verified with a status of 'Verified'.

[Assistant] SELECT e.full_name, COUNT(d.document_id) FROM government_services.documents d JOIN employees e ON d.verified_by_employee_id = e.employee_id WHERE d.verification_status = 'Verified' GROUP BY e.full_name;

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 text, application_id text, citizen_id text, document_type text, file_reference text, upload_timestamp timestamp, expiry_date date, verification_status text, verified_by_employee_id text, verification_timestamp timestamp )


[User] Show me all active policies with coverage limits above $1,000,000, along with the customer names and agent names, sorted by coverage limit in descending order.

[Assistant] SELECT p.policy_id, p.customer_id, p.agent_id, p.coverage_limit, p.premium_amount, p.start_date, p.end_date FROM insurance.policies p WHERE p.status = 'active' AND p.coverage_limit > 1000000 ORDER BY p.coverage_limit DESC;

[User] Actually, I need to see the customer's first and last name from the customers table and the agent's full name from the agents table as well.

[Assistant] SELECT p.policy_id, p.coverage_limit, p.premium_amount, c.first_name AS customer_first_name, c.last_name AS customer_last_name, a.first_name AS agent_first_name, a.last_name AS agent_last_name FROM insurance.policies p JOIN insurance.customers c ON p.customer_id = c.customer_id JOIN insurance.agents a ON p.agent_id = a.agent_id WHERE p.status = 'active' AND p.coverage_limit > 1000000 ORDER BY p.coverage_limit DESC;

[User] Now I also want to see the total number of claims each of these high-coverage policies has had.

[Assistant] SELECT p.policy_id, p.coverage_limit, p.premium_amount, c.first_name AS customer_first_name, c.last_name AS customer_last_name, a.first_name AS agent_first_name, a.last_name AS agent_last_name, COUNT(cl.claim_id) AS total_claims FROM insurance.policies p JOIN insurance.customers c ON p.customer_id = c.customer_id JOIN insurance.agents a ON p.agent_id = a.agent_id LEFT JOIN insurance.claims cl ON p.policy_id = cl.policy_id WHERE p.status = 'active' AND p.coverage_limit > 1000000 GROUP BY p.policy_id, p.coverage_limit, p.premium_amount, c.first_name, c.last_name, a.first_name, a.last_name ORDER BY p.coverage_limit DESC;

[User] Finally, filter these results to only show policies that have at least one claim and include the average settlement amount for those claims.

[Assistant] SELECT p.policy_id, p.coverage_limit, p.premium_amount, c.first_name AS customer_first_name, c.last_name AS customer_last_name, a.first_name AS agent_first_name, a.last_name AS agent_last_name, COUNT(cl.claim_id) AS total_claims, AVG(cl.settlement_amount) AS avg_settlement FROM insurance.policies p JOIN insurance.customers c ON p.customer_id = c.customer_id JOIN insurance.agents a ON p.agent_id = a.agent_id JOIN insurance.claims cl ON p.policy_id = cl.policy_id WHERE p.status = 'active' AND p.coverage_limit > 1000000 GROUP BY p.policy_id, p.coverage_limit, p.premium_amount, c.first_name, c.last_name, a.first_name, a.last_name HAVING COUNT(cl.claim_id) > 0 ORDER BY p.coverage_limit 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.policies ( policy_id.text, customer_id.text, product_id.text, agent_id.text, policy_number.text, start_date.date, end_date.date, premium_amount.numeric, coverage_limit.numeric, deductible.numeric, status.text, issued_at.timestamp, cancellation_date.date, cancellation_reason.text )
CREATE TABLE insurance.claims ( claim_id.text, policy_id.text, customer_id.text, incident_date.timestamp, reported_date.timestamp, description.text, estimated_loss.numeric, status.text, settlement_amount.numeric, settlement_date.date, claim_handler_id.text, police_report_number.text )
CREATE TABLE insurance.premium_payments ( payment_id.text, policy_id.text, customer_id.text, payment_date.timestamp, amount_paid.numeric, payment_method.text, transaction_reference.text, due_date.date, payment_period_start.date, payment_period_end.date, status.text )


[User] Which users participated in conversations where the hashtag 'AI' was used in associated posts? I want both usernames and conversation IDs.

[Assistant]
SELECT cp.user_id, cp.conversation_id
FROM social_media.conversation_participants cp
JOIN social_media.posts p ON cp.user_id = p.user_id
JOIN social_media.post_hashtags ph ON p.post_id = ph.post_id
JOIN social_media.hashtags h ON ph.hashtag_id = h.hashtag_id
WHERE h.tag_name = 'AI';

[User] Can you also include the date the user joined those conversations?

[Assistant]
SELECT cp.user_id, cp.conversation_id, cp.joined_at
FROM social_media.conversation_participants cp
JOIN social_media.posts p ON cp.user_id = p.user_id
JOIN social_media.post_hashtags ph ON p.post_id = ph.post_id
JOIN social_media.hashtags h ON ph.hashtag_id = h.hashtag_id
WHERE h.tag_name = 'AI';

[User] Now, restrict the results to only conversations that the user joined after January 1, 2024.

[Assistant]
SELECT cp.user_id, cp.conversation_id, cp.joined_at
FROM social_media.conversation_participants cp
JOIN social_media.posts p ON cp.user_id = p.user_id
JOIN social_media.post_hashtags ph ON p.post_id = ph.post_id
JOIN social_media.hashtags h ON ph.hashtag_id = h.hashtag_id
WHERE h.tag_name = 'AI' AND cp.joined_at > '2024-01-01';

[User] If the same user participated in multiple conversations for the same tag, show only distinct combinations of user and conversation.

[Assistant]
SELECT DISTINCT cp.user_id, cp.conversation_id, cp.joined_at
FROM social_media.conversation_participants cp
JOIN social_media.posts p ON cp.user_id = p.user_id
JOIN social_media.post_hashtags ph ON p.post_id = ph.post_id
JOIN social_media.hashtags h ON ph.hashtag_id = h.hashtag_id
WHERE h.tag_name = 'AI' AND cp.joined_at > '2024-01-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.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.likes ( like_id.text, user_id.text, post_id.text, comment_id.text, created_at.timestamp )
CREATE TABLE social_media.hashtags ( hashtag_id text, tag_name text, created_at timestamp )
CREATE TABLE social_media.post_hashtags ( post_hashtag_id text, post_id text, hashtag_id text )
CREATE TABLE social_media.conversation_participants ( participant_id character varying(64) NOT NULL, conversation_id character varying(64) NOT NULL, user_id character varying(64) NOT NULL, joined_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, last_read_at timestamp, PRIMARY KEY (participant_id), CONSTRAINT unique_user_conversation UNIQUE (conversation_id, user_id) )
CREATE TABLE social_media.notifications (
    notification_id character varying(64) NOT NULL, -- unique identifier for the notification
    recipient_user_id character varying(64) NOT NULL, -- user receiving the notification (FK to users.user_id)
    sender_user_id character varying(64), -- user triggering the notification (FK to users.user_id, can be null for system notifications)
    notification_type character varying(30) NOT NULL, -- type of notification ('like', 'comment', 'follow', 'mention', 'message')
    target_entity_id character varying(64), -- ID of the related entity (post_id, comment_id, user_id, conversation_id)
    target_entity_type character varying(20), -- type of the related entity ('post', 'comment', 'user', 'conversation')
    created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, -- timestamp notification was created
    read_at timestamp, -- timestamp notification was marked as read
    PRIMARY KEY (notification_id)
)


[User] List all hashtags that have never been associated with any post, showing hashtag_id and tag_name.

[Assistant]
SELECT h.hashtag_id, h.tag_name
FROM social_media.hashtags h
LEFT JOIN social_media.post_hashtags ph ON h.hashtag_id = ph.hashtag_id
WHERE ph.post_hashtag_id IS NULL;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE social_media.users (
    user_id character varying(64) NOT NULL,  -- unique identifier for the user
    username character varying(50) NOT NULL UNIQUE, -- user's unique handle
    email character varying(128) NOT NULL UNIQUE, -- user's email address
    password_hash text NOT NULL, -- hashed password
    full_name character varying(100), -- user's full name
    profile_picture_url text, -- URL to the profile picture
    bio text, -- short user biography
    location character varying(100), -- user's location
    created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, -- timestamp of account creation
    updated_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, -- timestamp of last profile update
    is_verified boolean NOT NULL DEFAULT false, -- verification status
    PRIMARY KEY (user_id)
)
CREATE TABLE social_media.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, conversation_id character varying(64) NOT NULL, sender_user_id character varying(64) NOT NULL, content text, media_url text, media_type character varying(20), sent_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, read_at timestamp, 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.notifications ( notification_id text PRIMARY KEY, recipient_user_id text, sender_user_id text, notification_type text, target_entity_id text, target_entity_type text, created_at timestamp, read_at timestamp )
CREATE TABLE social_media.user_settings ( setting_id text, user_id text, theme text, email_notifications_enabled boolean, push_notifications_enabled boolean, private_profile boolean, updated_at timestamp )


[User] Find all blocks that contain transactions where the amount is greater than 500, and include the block difficulty.

[Assistant] SELECT DISTINCT b.block_id, b.difficulty FROM blockchain.blocks b JOIN blockchain.transactions t ON b.block_id = t.block_id WHERE t.amount > 500;

[User] Now show me the average difficulty of these blocks compared to the average difficulty of all blocks.

[Assistant] SELECT 'High-value blocks' AS block_type, AVG(b.difficulty) AS avg_difficulty FROM blockchain.blocks b JOIN blockchain.transactions t ON b.block_id = t.block_id WHERE t.amount > 500 UNION SELECT 'All blocks' AS block_type, AVG(difficulty) AS avg_difficulty FROM blockchain.blocks;

[User] Can you also include the count of blocks in each category?

[Assistant] SELECT 'High-value blocks' AS block_type, AVG(b.difficulty) AS avg_difficulty, COUNT(DISTINCT b.block_id) AS block_count FROM blockchain.blocks b JOIN blockchain.transactions t ON b.block_id = t.block_id WHERE t.amount > 500 UNION SELECT 'All blocks' AS block_type, AVG(difficulty) AS avg_difficulty, COUNT(*) AS block_count FROM blockchain.blocks;

System:
You are an SQL statement expert. Given the table structure described by the CREATE TABLE statement, write an SQL query that provides the solution to the user's question.
##Table Structure
CREATE TABLE blockchain.blocks ( block_id text PRIMARY KEY, previous_block_id text, timestamp timestamp, nonce int, merkle_root text, difficulty int )
CREATE TABLE blockchain.transactions ( transaction_id text PRIMARY KEY, block_id text, sender_address text, receiver_address text, amount numeric, timestamp timestamp, signature text )
CREATE TABLE blockchain.addresses ( address_id text PRIMARY KEY, public_key text, balance numeric )
CREATE TABLE blockchain.nodes ( node_id text PRIMARY KEY, ip_address text, port int, last_seen timestamp )
CREATE TABLE blockchain.users ( user_id text PRIMARY KEY, username text, email text, password_hash text )
CREATE TABLE blockchain.smart_contracts ( contract_id text PRIMARY KEY, creator_address text, code text, timestamp timestamp )


[User] List all developers along with the total number of achievements available in games that they have developed.

[Assistant]
SELECT d.name, COUNT(a.achievement_id) AS total_achievements
FROM gaming_technology.developers d
JOIN gaming_technology.games g ON d.developer_id = g.developer_id
JOIN gaming_technology.achievements a ON g.game_id = a.game_id
GROUP BY d.developer_id, d.name;

[User] Actually, I want to see only those developers that have more than 20 total achievements in their games.

[Assistant]
SELECT d.name, COUNT(a.achievement_id) AS total_achievements
FROM gaming_technology.developers d
JOIN gaming_technology.games g ON d.developer_id = g.developer_id
JOIN gaming_technology.achievements a ON g.game_id = a.game_id
GROUP BY d.developer_id, d.name
HAVING COUNT(a.achievement_id) > 20;

[User] Can you also add the country of each developer in the result and sort by the total_achievements in descending order?

[Assistant]
SELECT d.name, d.country, COUNT(a.achievement_id) AS total_achievements
FROM gaming_technology.developers d
JOIN gaming_technology.games g ON d.developer_id = g.developer_id
JOIN gaming_technology.achievements a ON g.game_id = a.game_id
GROUP BY d.developer_id, d.name, d.country
HAVING COUNT(a.achievement_id) > 20
ORDER BY total_achievements DESC;

[User] My database does not have the table gaming_technology.games, can you revise the SQL using only the four provided tables?

[Assistant] -- There is no direct way to relate developers to achievements using only the four given tables because there are no games or mapping from developers to games. Therefore, this query cannot be performed with only the provided tables.

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.players ( player_id.uuid, username.text, email.text, password_hash.text, registration_date.timestamptz, last_login.timestamptz, country_code.text, status.text, profile_data.jsonb )
CREATE TABLE gaming_technology.developers ( developer_id.uuid, name.text, country.text, founded_year.integer, website.text, created_at.timestamptz )
CREATE TABLE gaming_technology.game_sessions ( session_id.uuid, player_id.uuid, game_id.uuid, server_id.uuid, start_time.timestamptz, end_time.timestamptz, duration_seconds.integer, score.integer, session_data.jsonb )
CREATE TABLE gaming_technology.achievements ( achievement_id.uuid, game_id.uuid, name.text, description.text, icon_url.text, points.integer, hidden.boolean )


[User] How many wallets does the user with ID 'user_123' have?

[Assistant] SELECT COUNT(*) FROM web3.wallets WHERE user_id = 'user_123';

[User] Can you list the addresses of those wallets?

[Assistant] SELECT address FROM web3.wallets WHERE user_id = 'user_123';

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 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 character varying(64) NOT NULL, contract_id character varying(64) NOT NULL, event_name character varying(128) NOT NULL, data text NOT NULL, emitted_at timestamp NOT NULL, transaction_id character varying(64) NOT NULL, log_index integer NOT NULL, PRIMARY KEY (event_id) )
CREATE TABLE web3.token_transfers ( transfer_id character varying(64) NOT NULL, token_id character varying(64) NOT NULL, from_address character varying(128) NOT NULL, to_address character varying(128) NOT NULL, value numeric(38,14) NOT NULL, transaction_id character varying(64) NOT NULL, log_index integer NOT NULL, PRIMARY KEY (transfer_id) )
CREATE TABLE web3.wallets ( wallet_id character varying(64) NOT NULL, user_id character varying(64) NOT NULL, address character varying(128) NOT NULL, private_key text NOT NULL, created_at timestamp NOT NULL, PRIMARY KEY (wallet_id) )
CREATE TABLE web3.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) )


[User] Show the wallet address and amount for the token with tick 'ordi', along with its maximum supply from the `token_info` table.

[Assistant] SELECT T1.wallet_address, T1.amount, T2.max_supply FROM token_balances AS T1 JOIN token_info AS T2 ON T1.tick = T2.tick WHERE T1.tick = 'ordi';

[User] Only show me the wallets that hold more than 5000 of this token.

[Assistant] SELECT T1.wallet_address, T1.amount, T2.max_supply FROM token_balances AS T1 JOIN token_info AS T2 ON T1.tick = T2.tick WHERE T1.tick = 'ordi' AND T1.amount > 5000;

[User] Could you also include the block timestamp for these balance entries?

[Assistant] SELECT T1.wallet_address, T1.amount, T2.max_supply, T1.block_timestamp FROM token_balances AS T1 JOIN token_info AS T2 ON T1.tick = T2.tick WHERE T1.tick = 'ordi' AND T1.amount > 5000;

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(6) NOT NULL, block_number bigint NOT NULL, transaction_hash varchar NOT NULL, transaction_index bigint NOT NULL, from_address varchar NOT NULL, contract_address varchar NOT NULL, symbol varchar NOT NULL, total_supply varchar NOT NULL, name varchar NOT NULL, decimals bigint NOT NULL, is_erc20 integer NOT NULL, is_erc721 integer NOT NULL, is_erc1155 integer NOT NULL, is_proxy integer NOT NULL, extra_info varchar NOT NULL, pk integer NOT NULL )
CREATE TABLE erc1155_approval_for_all ( block_number bigint NOT NULL, block_timestamp timestamp(3) NOT NULL, transaction_index integer NOT NULL, transaction_hash varchar(66) NOT NULL, log_index integer NOT NULL, contract_address varchar(42) NOT NULL )
CREATE TABLE erc20_balances ( block_number bigint NOT NULL, contract_address varchar NOT NULL, wallet_address varchar NOT NULL, amount varchar NOT NULL, pk varchar NOT NULL )
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 sui_coins ( object_id varchar NOT NULL, status varchar NOT NULL, coin_type varchar NOT NULL, balance varchar NOT NULL, owner varchar NOT NULL )
CREATE TABLE sui_nfts ( object_id varchar NOT NULL, status varchar NOT NULL, collection_type varchar NOT NULL, package_id varchar NOT NULL, previous_transaction varchar NOT NULL, display varchar NOT NULL, owner varchar NOT NULL, name varchar NOT NULL )
CREATE TABLE nft_metadata ( blockchain varchar NOT NULL, contract_address varchar NOT NULL, token_id varchar NOT NULL, contract_name varchar NOT NULL, erc_type varchar NOT NULL, amount bigint NOT NULL, minter varchar NOT NULL, owner varchar NOT NULL, mint_block_number bigint NOT NULL, mint_time bigint NOT NULL, mint_transaction_hash varchar NOT NULL, mint_price varchar NOT NULL, token_uri varchar NOT NULL, metadata varchar NOT NULL, name varchar NOT NULL, image_uri varchar NOT NULL, traits varchar NOT NULL, updated_at bigint NOT NULL, status varchar NOT NULL, rarity_score real NOT NULL, rarity_rank integer NOT NULL, unique_attribute_count integer NOT NULL, pk integer NOT NULL )
CREATE TABLE token_prices ( uuid varchar(36) NOT NULL, blockchain varchar(36) NOT NULL, address varchar(42) NOT NULL, decimals bigint NOT NULL, symbol varchar(36) NOT NULL, price real NOT NULL, timestamp timestamp(6) NOT NULL )
CREATE TABLE token_prices_latest ( blockchain varchar(36) NOT NULL, address varchar(42) NOT NULL, decimals bigint NOT NULL, symbol varchar(36) NOT NULL, price real NOT NULL, timestamp timestamp(6) NOT NULL )
CREATE TABLE erc20_approval ( block_number bigint NOT NULL, block_timestamp timestamp(6) NOT NULL, transaction_index integer NOT NULL, transaction_hash varchar NOT NULL, log_index integer NOT NULL, contract_address varchar NOT NULL, pk integer NOT NULL )
CREATE TABLE token_balances ( block_number bigint NOT NULL, block_timestamp timestamp(3) NOT NULL, tick varchar NOT NULL, wallet_address varchar(42) NOT NULL, total_supply decimal(38,0) NOT NULL, amount decimal(38,0) NOT NULL )
CREATE TABLE token_info ( block_timestamp timestamp(3) NOT NULL, block_number bigint NOT NULL, tx_index integer NOT NULL, tx_hash varchar(66) NOT NULL, tick varchar NOT NULL, max_supply decimal(38,0) NOT NULL, lim decimal(38,0) NOT NULL, wlim decimal(38,0) NOT NULL, dec integer NOT NULL, creator varchar(42) NOT NULL )
CREATE TABLE token_activities ( block_timestamp timestamp(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 NOT NULL, tick varchar 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 mud_holesky_redstone ( address varchar NOT NULL, table_id varchar NOT NULL, key_bytes varchar NOT NULL, key0 varchar NOT NULL, key1 varchar NOT NULL, static_data varchar NOT NULL, encoded_lengths varchar NOT NULL, dynamic_data varchar NOT NULL, is_deleted boolean NOT NULL, block_number bigint NOT NULL, log_index bigint NOT NULL )
CREATE TABLE token_balances_bitcoin ( block_number bigint NOT NULL, block_timestamp timestamp(3) NOT NULL, tick varchar(255) NOT NULL, wallet_address varchar(42) NOT NULL, total_supply varchar NOT NULL, amount varchar NOT NULL )
CREATE TABLE token_info_bitcoin ( block_timestamp timestamp(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_bitcoin ( 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(62) NOT NULL, to_address varchar(62) 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 NOT NULL, block_timestamp timestamp(3) NOT NULL, tick varchar(20) NOT NULL, wallet_address varchar(42) NOT NULL, total_supply decimal(38,0) NOT NULL, amount decimal(38,0) NOT NULL )
CREATE TABLE token_info_avalanche ( block_timestamp timestamp(3) NOT NULL, block_number bigint NOT NULL, tx_index integer NOT NULL, tx_hash varchar(66) NOT NULL, tick varchar(20) 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, minted decimal(38,0) NOT NULL, holders decimal(38,0) NOT NULL, txs decimal(38,0) NOT NULL, updated_timestamp timestamp(3) NOT NULL, completed_timestamp timestamp(3) NOT NULL, id varchar(255) NOT NULL )


[User] List the symbol and balance for all SUI coins, joining the `sui_coins` and `sui_coins_metadata` tables.

[Assistant] SELECT T2.symbol, T1.balance FROM sui_coins AS T1 INNER JOIN sui_coins_metadata AS T2 ON T1.object_id = T2.object_id

[User] Only show results where the balance is greater than 1000000.

[Assistant] SELECT T2.symbol, T1.balance FROM sui_coins AS T1 INNER JOIN sui_coins_metadata AS T2 ON T1.object_id = T2.object_id WHERE CAST(T1.balance AS REAL) > 1000000

[User] Filter this list to only include coins with the symbol 'SUI'.

[Assistant] SELECT T2.symbol, T1.balance FROM sui_coins AS T1 INNER JOIN sui_coins_metadata AS T2 ON T1.object_id = T2.object_id WHERE CAST(T1.balance AS REAL) > 1000000 AND T2.symbol = 'SUI'

System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE token_metas ( block_timestamp timestamp, block_number bigint, transaction_hash varchar, transaction_index bigint, from_address varchar, contract_address varchar, symbol varchar, total_supply varchar, name varchar, decimals bigint, is_erc20 integer, is_erc721 integer, is_erc1155 integer, is_proxy integer, extra_info varchar, pk integer )
CREATE TABLE erc1155_approval_for_all ( block_number bigint, block_timestamp timestamp, transaction_index integer, transaction_hash varchar, log_index integer, contract_address varchar )
CREATE TABLE erc20_balances_historical ( block_number bigint, contract_address varchar, wallet_address varchar, amount varchar, pk integer )
CREATE TABLE nft_holder_historical ( block_number bigint, contract_address varchar, wallet_address varchar, token_id varchar, contract_type varchar, amount varchar, pk integer )
CREATE TABLE sui_coins ( object_id varchar, status varchar, coin_type varchar, balance varchar, owner varchar )
CREATE TABLE sui_coins_metadata ( object_id varchar, coin_type varchar, status varchar, decimals bigint, description varchar, icon_url varchar, symbol varchar, name varchar )
CREATE TABLE sui_nfts ( object_id varchar, status varchar, collection_type varchar, package_id varchar, previous_transaction varchar, display varchar, owner varchar, name varchar )
CREATE TABLE nft_metadata ( blockchain varchar, contract_address varchar, token_id varchar, contract_name varchar, erc_type varchar, amount bigint, minter varchar, owner varchar, mint_block_number bigint, mint_time bigint, mint_transaction_hash varchar, mint_price varchar, token_uri varchar, metadata varchar, name varchar, image_uri varchar, traits varchar, updated_at bigint, status varchar, rarity_score real, rarity_rank integer, unique_attribute_count integer, pk integer )
CREATE TABLE nft_collections ( blockchain varchar, contract_address varchar, name varchar, symbol varchar, deploy_block_number bigint, deploy_block_time bigint, erc_type varchar, owner varchar, traits varchar, description varchar, slug varchar, media_info varchar, image_url varchar, banner_image_url varchar, updated_at bigint, banner varchar, token_count bigint, floor_price varchar, floor_price_symbol varchar, floor_price_contract varchar, pk integer )
CREATE TABLE token_prices ( uuid varchar, blockchain varchar, address varchar, decimals bigint, symbol varchar, price real, timestamp timestamp )
CREATE TABLE token_prices_latest ( blockchain varchar, address varchar, decimals bigint, symbol varchar, price real, timestamp timestamp )
CREATE TABLE erc20_approval ( block_number bigint, block_timestamp timestamp, transaction_index integer, transaction_hash varchar, log_index integer, contract_address varchar, pk integer )
CREATE TABLE token_balances ( block_number bigint, block_timestamp timestamp, tick varchar, wallet_address varchar, total_supply decimal, amount decimal )
CREATE TABLE token_info ( block_timestamp timestamp, block_number bigint, tx_index integer, tx_hash varchar, tick varchar, max_supply decimal, lim decimal, wlim decimal, dec integer, creator varchar )
CREATE TABLE token_activities ( block_timestamp timestamp, block_number bigint, tx_index integer, tx_hash varchar, log_index integer, type varchar, tick varchar, id varchar, amt decimal, from_address varchar, to_address varchar )
CREATE TABLE mud_holesky_redstone ( address varchar, table_id varchar, key_bytes varchar, key0 varchar, key1 varchar, static_data varchar, encoded_lengths varchar, dynamic_data varchar, is_deleted boolean, block_number bigint, log_index bigint )
CREATE TABLE token_balances_bitcoin ( block_number bigint, block_timestamp timestamp, tick varchar, wallet_address varchar, total_supply varchar, amount varchar )
CREATE TABLE token_info_bitcoin ( block_timestamp timestamp, block_number bigint, tx_index integer, tx_hash varchar, tick varchar, max_supply decimal, lim decimal, wlim decimal, dec integer, creator varchar )
CREATE TABLE token_activities_bitcoin ( block_timestamp timestamp, block_number bigint, tx_index integer, tx_hash varchar, log_index integer, type varchar, tick varchar, id varchar, amt decimal, from_address varchar, to_address varchar )
CREATE TABLE token_activities_avalanche ( block_timestamp timestamp, block_number bigint, tx_index integer, tx_hash varchar, log_index integer, type varchar, tick varchar, id varchar, amt decimal, from_address varchar, to_address varchar )
CREATE TABLE token_balances_avalanche ( block_number bigint, block_timestamp timestamp, tick varchar, wallet_address varchar, total_supply decimal, amount decimal )
CREATE TABLE token_info_avalanche ( block_timestamp timestamp, block_number bigint, tx_index integer, tx_hash varchar, tick varchar, max_supply decimal, lim decimal, wlim decimal, dec integer, creator varchar, minted decimal, holders decimal, txs decimal, updated_timestamp timestamp, completed_timestamp timestamp, id varchar )