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 financial_services.employees (
    employee_id character varying(64) NOT NULL,  -- unique identifier for the employee
    first_name character varying(100) NOT NULL,
    last_name character varying(100) NOT NULL,
    job_title character varying(100) NOT NULL, -- e.g., Teller, Branch Manager, Financial Advisor, Analyst
    department character varying(100), -- e.g., Retail Banking, Wealth Management, IT
    branch_id character varying(64), -- Identifier for the branch they work at (if applicable)
    email character varying(128) NOT NULL UNIQUE,
    phone_extension character varying(20),
    hire_date date NOT NULL,
    termination_date date, -- Date of termination, null if currently employed
    manager_id character varying(64), -- Self-referencing key for manager relationship
    status character varying(32) NOT NULL, -- e.g., Active, Terminated, On Leave
    PRIMARY KEY (employee_id),
    FOREIGN KEY (branch_id) REFERENCES financial_services.branches(branch_id), -- Assuming a branches table exists
    FOREIGN KEY (manager_id) REFERENCES financial_services.employees(employee_id)
)

[User] List employees whose job title is different from their manager's job title, showing the employee's full name and their manager's full name.

[Assistant] SELECT e.first_name, e.last_name, m.first_name AS manager_first_name, m.last_name AS manager_last_name FROM financial_services.employees AS e JOIN financial_services.employees AS m ON e.manager_id = m.employee_id WHERE e.job_title <> m.job_title;

[User] Only include employees from the 'IT' department.

[Assistant] SELECT e.first_name, e.last_name, m.first_name AS manager_first_name, m.last_name AS manager_last_name FROM financial_services.employees AS e JOIN financial_services.employees AS m ON e.manager_id = m.employee_id WHERE e.job_title <> m.job_title AND e.department = 'IT';

[User] Add the job titles for both the employee and manager, and order by employee's last name.

[Assistant] SELECT e.first_name, e.last_name, e.job_title AS employee_job_title, m.first_name AS manager_first_name, m.last_name AS manager_last_name, m.job_title AS manager_job_title FROM financial_services.employees AS e JOIN financial_services.employees AS m ON e.manager_id = m.employee_id WHERE e.job_title <> m.job_title AND e.department = 'IT' ORDER BY e.last_name ASC;

[User] Give me a count of employees hired in each department for employees currently active or terminated.

[Assistant] SELECT department, status, COUNT(employee_id) AS employee_count FROM financial_services.employees WHERE status IN ('Active', 'Terminated') GROUP BY department, status;

[User] For the terminated employees in those departments, also include the average tenure in days, considering only those with a termination date.

[Assistant] SELECT department, SUM(CASE WHEN status = 'Active' THEN 1 ELSE 0 END) AS active_count, SUM(CASE WHEN status = 'Terminated' THEN 1 ELSE 0 END) AS terminated_count, AVG(CASE WHEN status = 'Terminated' AND termination_date IS NOT NULL THEN EXTRACT(EPOCH FROM (termination_date - hire_date)) / 86400.0 ELSE NULL END) AS avg_terminated_tenure_days FROM financial_services.employees GROUP BY department;

[User] Only show departments with more than 5 active employees and order by the active employee count descending.

[Assistant] SELECT department, SUM(CASE WHEN status = 'Active' THEN 1 ELSE 0 END) AS active_count, SUM(CASE WHEN status = 'Terminated' THEN 1 ELSE 0 END) AS terminated_count, AVG(CASE WHEN status = 'Terminated' AND termination_date IS NOT NULL THEN EXTRACT(EPOCH FROM (termination_date - hire_date)) / 86400.0 ELSE NULL END) AS avg_terminated_tenure_days FROM financial_services.employees GROUP BY department HAVING SUM(CASE WHEN status = 'Active' THEN 1 ELSE 0 END) > 5 ORDER BY active_count DESC;

[User] Report the number of employees for each department, broken down by their employment status.

[Assistant] SELECT department, status, COUNT(*) AS employee_count FROM financial_services.employees GROUP BY department, status

[User] Only show results for departments that have at least 10 employees in total (across all statuses).

[Assistant]
SELECT department,
       status,
       COUNT(*) AS employee_count
FROM financial_services.employees
GROUP BY department, status;

[User] Exclude any groups where the employee count is less than 5.

[Assistant]
SELECT department,
       status,
       COUNT(*) AS employee_count
FROM financial_services.employees
GROUP BY department, status
HAVING COUNT(*) >= 5;

[User] Finally, order the results by department name descending.

[Assistant]
SELECT department,
       status,
       COUNT(*) AS employee_count
FROM financial_services.employees
GROUP BY department, status
HAVING COUNT(*) >= 5
ORDER BY department DESC;

[User] Provide a list of all employees and their corresponding managers. Please display the full name for both the employee and their manager.

[Assistant] SELECT e.first_name || ' ' || e.last_name AS employee_name, m.first_name || ' ' || m.last_name AS manager_name FROM financial_services.employees AS e LEFT JOIN financial_services.employees AS m ON e.manager_id = m.employee_id

[User] Restrict the list to only include employees who are currently in 'Active' status.

[Assistant] SELECT e.first_name || ' ' || e.last_name AS employee_name, m.first_name || ' ' || m.last_name AS manager_name FROM financial_services.employees AS e LEFT JOIN financial_services.employees AS m ON e.manager_id = m.employee_id WHERE e.status = 'Active'

[User] For each department, what is the earliest and latest employee hire date?

[Assistant] SELECT department, MIN(hire_date) AS earliest_hire_date, MAX(hire_date) AS latest_hire_date FROM financial_services.employees GROUP BY department;

[User] Include the total number of employees for each department.

[Assistant] SELECT department, MIN(hire_date) AS earliest_hire_date, MAX(hire_date) AS latest_hire_date, COUNT(employee_id) AS total_employees FROM financial_services.employees GROUP BY department;

[User] Only show departments with more than 3 employees.

[Assistant] SELECT department, MIN(hire_date) AS earliest_hire_date, MAX(hire_date) AS latest_hire_date, COUNT(employee_id) AS total_employees FROM financial_services.employees GROUP BY department HAVING COUNT(employee_id) > 3;

[User] Show me the full names and job titles of all employees along with their managers’ full names in the same result.

[Assistant] SELECT e.employee_id, e.first_name || ' ' || e.last_name AS employee_name, e.job_title, m.first_name || ' ' || m.last_name AS manager_name FROM financial_services.employees e LEFT JOIN financial_services.employees m ON e.manager_id = m.employee_id;

[User] Only include employees whose managers are from a different department.

[Assistant] SELECT e.employee_id, e.first_name || ' ' || e.last_name AS employee_name, e.job_title, m.first_name || ' ' || m.last_name AS manager_name FROM financial_services.employees e LEFT JOIN financial_services.employees m ON e.manager_id = m.employee_id WHERE e.department IS DISTINCT FROM m.department;

[User] Can you add the departments of both the employee and the manager to the result?

[Assistant] SELECT e.employee_id, e.first_name || ' ' || e.last_name AS employee_name, e.department AS employee_department, e.job_title, m.first_name || ' ' || m.last_name AS manager_name, m.department AS manager_department FROM financial_services.employees e LEFT JOIN financial_services.employees m ON e.manager_id = m.employee_id WHERE e.department IS DISTINCT FROM m.department;

[User] Now, filter the list to only show employees hired after 2020-01-01.

[Assistant] SELECT e.employee_id, e.first_name || ' ' || e.last_name AS employee_name, e.department AS employee_department, e.job_title, m.first_name || ' ' || m.last_name AS manager_name, m.department AS manager_department FROM financial_services.employees e LEFT JOIN financial_services.employees m ON e.manager_id = m.employee_id WHERE e.department IS DISTINCT FROM m.department AND e.hire_date > '2020-01-01';


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE legal_services.invoices ( invoice_id.text, invoice_number.text, client_id.text, case_id.text, issue_date.date, due_date.date, total_amount.numeric, amount_paid.numeric, status.text, payment_date.timestamp, notes.text, created_at.timestamp )
CREATE TABLE legal_services.appointments ( appointment_id.text, client_id.text, lawyer_id.text, case_id.text, start_time.timestamp, end_time.timestamp, location.text, subject.text, notes.text, status.text, created_at.timestamp )

[User] For each case, show the total amount of all invoices and the number of scheduled appointments. Only include cases that have both an invoice and at least one appointment.

[Assistant]
SELECT i.case_id, SUM(i.total_amount) AS total_invoice_amount, COUNT(DISTINCT a.appointment_id) AS scheduled_appointments
FROM legal_services.invoices i
JOIN legal_services.appointments a ON i.case_id = a.case_id
WHERE a.status = 'Scheduled'
GROUP BY i.case_id;

[User] Actually, can you split the scheduled appointments count by each client within the case? So I want case_id, client_id, total_invoice_amount, and count of scheduled appointments per client.

[Assistant]
SELECT i.case_id, a.client_id, SUM(i.total_amount) AS total_invoice_amount, COUNT(a.appointment_id) AS scheduled_appointments
FROM legal_services.invoices i
JOIN legal_services.appointments a ON i.case_id = a.case_id
WHERE a.status = 'Scheduled'
GROUP BY i.case_id, a.client_id;

[User] Now, please only include cases where the total_invoice_amount is greater than 10000.

[Assistant]
SELECT i.case_id, a.client_id, SUM(i.total_amount) AS total_invoice_amount, COUNT(a.appointment_id) AS scheduled_appointments
FROM legal_services.invoices i
JOIN legal_services.appointments a ON i.case_id = a.case_id
WHERE a.status = 'Scheduled'
GROUP BY i.case_id, a.client_id
HAVING SUM(i.total_amount) > 10000;

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

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

[User] Find the total number of distinct lawyers and distinct documents in the database.

[Assistant] SELECT (SELECT COUNT(DISTINCT lawyer_id) FROM legal_services.lawyers) AS distinct_lawyer_count, (SELECT COUNT(DISTINCT document_id) FROM legal_services.documents) AS distinct_document_count;

[User] Get all documents uploaded by lawyers who are partners.

[Assistant]
SELECT d.document_id, d.document_name, d.case_id, d.upload_timestamp
FROM legal_services.documents d
JOIN legal_services.lawyers l ON d.uploaded_by_lawyer_id = l.lawyer_id
WHERE l.is_partner = true;

[User] Actually, I want to see for each document the appointment subjects that are related to the same case along with the document name.

[Assistant]
SELECT d.document_name, a.subject
FROM legal_services.documents d
JOIN legal_services.lawyers l ON d.uploaded_by_lawyer_id = l.lawyer_id
JOIN legal_services.appointments a ON d.case_id = a.case_id
WHERE l.is_partner = true;

[User] Only include documents that were uploaded in 2024.

[Assistant]
SELECT d.document_name, a.subject
FROM legal_services.documents d
JOIN legal_services.lawyers l ON d.uploaded_by_lawyer_id = l.lawyer_id
JOIN legal_services.appointments a ON d.case_id = a.case_id
WHERE l.is_partner = true AND EXTRACT(YEAR FROM d.upload_timestamp) = 2024;

[User] Show me the subjects and start times of all appointments along with the document names of any documents uploaded for the associated case.

[Assistant]
SELECT a.subject, a.start_time, d.document_name
FROM legal_services.appointments a
JOIN legal_services.documents d ON a.case_id = d.case_id;

[User] List the first name, last name, and specialization of all lawyers who have uploaded at least one document.

[Assistant] SELECT T1.first_name, T1.last_name, T1.specialization FROM legal_services.lawyers AS T1 JOIN legal_services.documents AS T2 ON T1.lawyer_id = T2.uploaded_by_lawyer_id GROUP BY T1.lawyer_id, T1.first_name, T1.last_name, T1.specialization;

[User] Show me case numbers, names, and related invoice numbers.

[Assistant] SELECT T1.case_number, T1.case_name, T2.invoice_number FROM legal_services.cases AS T1 JOIN legal_services.invoices AS T2 ON T1.case_id = T2.case_id;

[User] Only include cases that are currently 'Open'.

[Assistant] SELECT T1.case_number, T1.case_name, T2.invoice_number FROM legal_services.cases AS T1 JOIN legal_services.invoices AS T2 ON T1.case_id = T2.case_id WHERE T1.status = 'Open';

[User] Also, only show invoices that have a 'Paid' status.

[Assistant] SELECT T1.case_number, T1.case_name, T2.invoice_number FROM legal_services.cases AS T1 JOIN legal_services.invoices AS T2 ON T1.case_id = T2.case_id WHERE T1.status = 'Open' AND T2.status = 'Paid';


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

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

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

[User] Can you assist me in finding all staff members assigned to a specific station with station_id 'station_xyz', including the station details and their roles?

[Assistant]
db.staff.aggregate([
    {
        $lookup: {
            from: 'stations',
            localField: 'primary_station_id',
            foreignField: 'station_id',
            as: 'station_details'
        }
    },
    {
        $match: {
            'primary_station_id': 'station_xyz'
        }
    },
    {
        $project: {
            staff_id: 1,
            first_name: 1,
            last_name: 1,
            role: 1,
            'station_details.station_name': 1,
            'station_details.city': 1
        }
    }
]);

[User] I noticed that some staff might not have a primary station assigned. Can you revise the query to include staff who might be associated with the station in other ways, if possible?

[Assistant]
db.staff.aggregate([
    {
        $lookup: {
            from: 'stations',
            localField: 'primary_station_id',
            foreignField: 'station_id',
            as: 'station_details'
        }
    },
    {
        $match: {
            $or: [
                { 'primary_station_id': 'station_xyz' },
                { 'primary_station_id': null }
            ]
        }
    },
    {
        $project: {
            staff_id: 1,
            first_name: 1,
            last_name: 1,
            role: 1,
            'station_details.station_name': 1,
            'station_details.city': 1
        }
    }
]);

[User] Can you help me retrieve the details of all bookings for a specific station with station_id 'station_xyz', including the associated schedule and passenger information?

[Assistant]
db.bookings.aggregate([
    {
        $lookup: {
            from: 'schedules',
            localField: 'schedule_id',
            foreignField: 'schedule_id',
            as: 'schedule_details'
        }
    },
    {
        $lookup: {
            from: 'passengers',
            localField: 'passenger_id',
            foreignField: 'passenger_id',
            as: 'passenger_details'
        }
    },
    {
        $lookup: {
            from: 'stations',
            localField: 'schedule_details.origin_station_id',
            foreignField: 'station_id',
            as: 'origin_station'
        }
    },
    {
        $match: {
            'origin_station.station_id': 'station_xyz'
        }
    },
    {
        $project: {
            booking_id: 1,
            booking_datetime: 1,
            status: 1,
            total_price: 1,
            'schedule_details.schedule_id': 1,
            'schedule_details.departure_datetime': 1,
            'passenger_details.first_name': 1,
            'passenger_details.last_name': 1,
            'origin_station.station_name': 1
        }
    }
]);

[User] Can you modify the query to include only bookings with a status of 'Pending'?

[Assistant]
db.bookings.aggregate([
    {
        $lookup: {
            from: 'schedules',
            localField: 'schedule_id',
            foreignField: 'schedule_id',
            as: 'schedule_details'
        }
    },
    {
        $lookup: {
            from: 'passengers',
            localField: 'passenger_id',
            foreignField: 'passenger_id',
            as: 'passenger_details'
        }
    },
    {
        $lookup: {
            from: 'stations',
            localField: 'schedule_details.origin_station_id',
            foreignField: 'station_id',
            as: 'origin_station'
        }
    },
    {
        $match: {
            'origin_station.station_id': 'station_xyz',
            status: 'Pending'
        }
    },
    {
        $project: {
            booking_id: 1,
            booking_datetime: 1,
            status: 1,
            total_price: 1,
            'schedule_details.schedule_id': 1,
            'schedule_details.departure_datetime': 1,
            'passenger_details.first_name': 1,
            'passenger_details.last_name': 1,
            'origin_station.station_name': 1
        }
    }
]);

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

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


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
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] Show the first and last name of each passenger along with the total number of bookings they have made.

[Assistant] SELECT p.first_name, p.last_name, COUNT(b.booking_id) AS booking_count FROM transportation.passengers p LEFT JOIN transportation.bookings b ON p.passenger_id = b.passenger_id GROUP BY p.passenger_id, p.first_name, p.last_name;

[User] Now, only include passengers who have made more than 5 bookings.

[Assistant] SELECT p.first_name, p.last_name, COUNT(b.booking_id) AS booking_count FROM transportation.passengers p JOIN transportation.bookings b ON p.passenger_id = b.passenger_id GROUP BY p.passenger_id, p.first_name, p.last_name HAVING COUNT(b.booking_id) > 5;

[User] List all passengers born before 1990 with their first and last names and email addresses.

[Assistant] SELECT first_name, last_name, email FROM transportation.passengers WHERE date_of_birth < '1990-01-01';

[User] Can you also include their phone numbers in the result?

[Assistant] SELECT first_name, last_name, email, phone_number FROM transportation.passengers WHERE date_of_birth < '1990-01-01';

[User] Now, filter it further to only passengers who have an email address registered.

[Assistant] SELECT first_name, last_name, email, phone_number FROM transportation.passengers WHERE date_of_birth < '1990-01-01' AND email IS NOT NULL;

[User] Sort the final result by last name in ascending order.

[Assistant] SELECT first_name, last_name, email, phone_number FROM transportation.passengers WHERE date_of_birth < '1990-01-01' AND email IS NOT NULL ORDER BY last_name ASC;

[User] Show me the email and full name of passengers who are enrolled in a loyalty program, along with the date they joined, ordered by most recent sign-up.

[Assistant] SELECT email, CONCAT(first_name, ' ', last_name) AS full_name, created_at FROM transportation.passengers WHERE loyalty_program_id IS NOT NULL ORDER BY created_at DESC;

[User] Show me the list of all passengers who do not have a loyalty program membership, including their passenger ID and the date their record was created.

[Assistant] SELECT passenger_id, created_at FROM transportation.passengers WHERE loyalty_program_id IS NULL;

[User] Show me the first name, last name, and email address for passengers who have made a booking with 'Completed' status.

[Assistant] SELECT DISTINCT p.first_name, p.last_name, p.email FROM transportation.passengers p JOIN transportation.bookings b ON p.passenger_id = b.passenger_id WHERE b.status = 'Completed';

[User] From this list, can you also include the booking time and fare for these completed bookings?

[Assistant] SELECT p.first_name, p.last_name, p.email, b.booking_time, b.fare FROM transportation.passengers p JOIN transportation.bookings b ON p.passenger_id = b.passenger_id WHERE b.status = 'Completed';

[User] Now, order the results by booking time in descending order and only show bookings with a fare greater than 200.

[Assistant] SELECT p.first_name, p.last_name, p.email, b.booking_time, b.fare FROM transportation.passengers p JOIN transportation.bookings b ON p.passenger_id = b.passenger_id WHERE b.status = 'Completed' AND b.fare > 200 ORDER BY b.booking_time DESC;

[User] Please show me the first name, last name, and date of birth for all passengers born before January 1, 1990.

[Assistant] SELECT first_name, last_name, date_of_birth FROM transportation.passengers WHERE date_of_birth < '1990-01-01';

[User] From that group, could you further filter to only include those whose records were added on or after January 1, 2022?

[Assistant] SELECT first_name, last_name, date_of_birth FROM transportation.passengers WHERE date_of_birth < '1990-01-01' AND created_at >= '2022-01-01';

[User] Finally, order the results of this refined list by their date of birth in ascending order.

[Assistant] SELECT first_name, last_name, date_of_birth FROM transportation.passengers WHERE date_of_birth < '1990-01-01' AND created_at >= '2022-01-01' ORDER BY date_of_birth ASC;

[User] Show me all bookings with the passenger's full name and the booking status.

[Assistant]
SELECT b.booking_id, p.first_name || ' ' || p.last_name AS passenger_full_name, b.status
FROM transportation.bookings b
JOIN transportation.passengers p ON b.passenger_id = p.passenger_id;

[User] Please only include bookings where the status is 'Completed'.

[Assistant]
SELECT b.booking_id, p.first_name || ' ' || p.last_name AS passenger_full_name, b.status
FROM transportation.bookings b
JOIN transportation.passengers p ON b.passenger_id = p.passenger_id
WHERE b.status = 'Completed';

[User] Add the fare amount and booking time for each completed booking.

[Assistant]
SELECT b.booking_id, p.first_name || ' ' || p.last_name AS passenger_full_name, b.status, b.fare, b.booking_time
FROM transportation.bookings b
JOIN transportation.passengers p ON b.passenger_id = p.passenger_id
WHERE b.status = 'Completed';

[User] Limit the results to the latest 10 completed bookings by booking_time.

[Assistant]
SELECT b.booking_id, p.first_name || ' ' || p.last_name AS passenger_full_name, b.status, b.fare, b.booking_time
FROM transportation.bookings b
JOIN transportation.passengers p ON b.passenger_id = p.passenger_id
WHERE b.status = 'Completed'
ORDER BY b.booking_time DESC
LIMIT 10;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE insurance.policies ( policy_id character varying(64) NOT NULL, customer_id character varying(64) NOT NULL, product_id character varying(64) NOT NULL, agent_id character varying(64), policy_number character varying(100) NOT NULL UNIQUE, start_date date NOT NULL, end_date date NOT NULL, premium_amount numeric(12, 2) NOT NULL, coverage_limit numeric(15, 2) NOT NULL, deductible numeric(10, 2) NOT NULL, status character varying(30) NOT NULL, issued_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, cancellation_date date, cancellation_reason text, PRIMARY KEY (policy_id) )
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.agents ( agent_id text PRIMARY KEY, first_name text, last_name text, agency_name text, license_number text, license_state text, contact_email text, contact_phone text, hire_date date, termination_date date, status text, commission_rate numeric, manager_id text )

[User] Show all policies that started before January 1, 2022, including policy_id, policy_number, start_date, and status.

[Assistant]
SELECT policy_id, policy_number, start_date, status
FROM insurance.policies
WHERE start_date < '2022-01-01';

[User] How many claims were reported in the last 90 days?

[Assistant] SELECT COUNT(*) FROM claims WHERE reported_date >= CURRENT_DATE - INTERVAL '90 days'

[User] List all policies that have at least one beneficiary with a 'Child' relationship, showing policy number, policy status, and the number of child beneficiaries for that policy.

[Assistant] SELECT T1.policy_number, T1.status, COUNT(T2.beneficiary_id) AS child_beneficiary_count FROM policies AS T1 JOIN policy_beneficiaries AS T2 ON T1.policy_id = T2.policy_id WHERE T2.relationship = 'Child' GROUP BY T1.policy_id, T1.policy_number, T1.status HAVING COUNT(T2.beneficiary_id) >= 1

[User] Can you also include the total premium amount for these policies?

[Assistant] SELECT T1.policy_number, T1.status, T1.premium_amount, COUNT(T2.beneficiary_id) AS child_beneficiary_count FROM policies AS T1 JOIN policy_beneficiaries AS T2 ON T1.policy_id = T2.policy_id WHERE T2.relationship = 'Child' GROUP BY T1.policy_id, T1.policy_number, T1.status, T1.premium_amount HAVING COUNT(T2.beneficiary_id) >= 1

[User] For each agent, show their agent_id, first and last name, and the total estimated loss for all claims they have handled as a claim handler.

[Assistant]
SELECT a.agent_id, a.first_name, a.last_name, SUM(c.estimated_loss) AS total_estimated_loss
FROM insurance.agents a
JOIN insurance.claims c ON a.agent_id = c.claim_handler_id
GROUP BY a.agent_id, a.first_name, a.last_name;

[User] Actually, please only show agents with a total estimated loss above 100000.

[Assistant]
SELECT a.agent_id, a.first_name, a.last_name, SUM(c.estimated_loss) AS total_estimated_loss
FROM insurance.agents a
JOIN insurance.claims c ON a.agent_id = c.claim_handler_id
GROUP BY a.agent_id, a.first_name, a.last_name
HAVING SUM(c.estimated_loss) > 100000;

[User] Show me the incident date, estimated loss, and the associated product name for all claims with an estimated loss greater than 20000.

[Assistant]
SELECT c.incident_date, c.estimated_loss, p.product_name
FROM insurance.claims c
JOIN insurance.policies pol ON c.policy_id = pol.policy_id
JOIN insurance.insurance_products p ON pol.product_id = p.product_id
WHERE c.estimated_loss > 20000;

[User] Show me claim IDs and the file names of any documents associated with claims filed before January 1, 2024.

[Assistant]
SELECT cd.claim_id, cd.file_name
FROM insurance.claims c
JOIN insurance.claim_documents cd ON c.claim_id = cd.claim_id
WHERE c.incident_date < '2024-01-01';

[User] Only include documents where the file size is less than 1 MB.

[Assistant]
SELECT cd.claim_id, cd.file_name
FROM insurance.claims c
JOIN insurance.claim_documents cd ON c.claim_id = cd.claim_id
WHERE c.incident_date < '2024-01-01'
  AND cd.file_size_bytes < 1048576;

[User] Add the document type to the results and sort by file size ascending.

[Assistant]
SELECT cd.claim_id, cd.file_name, cd.document_type, cd.file_size_bytes
FROM insurance.claims c
JOIN insurance.claim_documents cd ON c.claim_id = cd.claim_id
WHERE c.incident_date < '2024-01-01'
  AND cd.file_size_bytes < 1048576
ORDER BY cd.file_size_bytes ASC;

[User] Sorry, I got an error about NULL file sizes. Please exclude records where the file size is NULL.

[Assistant]
SELECT cd.claim_id, cd.file_name, cd.document_type, cd.file_size_bytes
FROM insurance.claims c
JOIN insurance.claim_documents cd ON c.claim_id = cd.claim_id
WHERE c.incident_date < '2024-01-01'
  AND cd.file_size_bytes IS NOT NULL
  AND cd.file_size_bytes < 1048576
ORDER BY cd.file_size_bytes ASC;

[User] List all insurance products along with their product type and creation date.

[Assistant]
SELECT product_name, product_type, created_at
FROM insurance.insurance_products;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE trading_platform.wallets ( wallet_id.text, user_id.text, address.text, private_key.text, created_at.timestamp )
CREATE TABLE trading_platform.orders ( order_id.text, user_id.text, wallet_id.text, asset_id.text, order_type.text, quantity.numeric, price.numeric, status.text, created_at.timestamp )

[User] List the order ID, type, and quantity for all orders placed using the wallet with ID 'wallet123'.

[Assistant] SELECT order_id, order_type, quantity FROM orders WHERE wallet_id = 'wallet123'

[User] Also include the creation date of the wallet that placed the order.

[Assistant] SELECT T1.order_id, T1.order_type, T1.quantity, T2.created_at AS wallet_created_at FROM orders AS T1 JOIN wallets AS T2 ON T1.wallet_id = T2.wallet_id WHERE T1.wallet_id = 'wallet123'

[User] Actually, ignore the specific wallet ID. Show the same information for all orders, but only include orders placed using wallets created before '2023-12-31'.

[Assistant] SELECT T1.order_id, T1.order_type, T1.quantity, T2.created_at AS wallet_created_at FROM orders AS T1 JOIN wallets AS T2 ON T1.wallet_id = T2.wallet_id WHERE T2.created_at < '2023-12-31'

[User] Filter that list further to only show 'sell' orders.

[Assistant] SELECT T1.order_id, T1.order_type, T1.quantity, T2.created_at AS wallet_created_at FROM orders AS T1 JOIN wallets AS T2 ON T1.wallet_id = T2.wallet_id WHERE T2.created_at < '2023-12-31' AND T1.order_type = 'sell'

[User] Show the number of wallets created each month in 2024, showing the year and month.

[Assistant] SELECT EXTRACT(YEAR FROM created_at) AS year, EXTRACT(MONTH FROM created_at) AS month, COUNT(*) FROM wallets WHERE EXTRACT(YEAR FROM created_at) = 2024 GROUP BY 1, 2 ORDER BY 1, 2

[User] List all orders, showing order ID, type, quantity, and price, that were placed using a wallet created after '2024-01-01'.

[Assistant] SELECT T1.order_id, T1.order_type, T1.quantity, T1.price FROM orders AS T1 JOIN wallets AS T2 ON T1.wallet_id = T2.wallet_id WHERE T2.created_at > '2024-01-01'

[User] From that list, only show orders with 'completed' status.

[Assistant] SELECT T1.order_id, T1.order_type, T1.quantity, T1.price FROM orders AS T1 JOIN wallets AS T2 ON T1.wallet_id = T2.wallet_id WHERE T2.created_at > '2024-01-01' AND T1.status = 'completed'

[User] List all wallets created before '2024-01-01', including the wallet_id, user_id, and creation date.

[Assistant] SELECT wallet_id, user_id, created_at FROM wallets WHERE created_at < '2024-01-01';

[User] Now, from that list, only include wallets belonging to users who also have created at least one wallet on or after '2024-01-01'.

[Assistant] SELECT w1.wallet_id, w1.user_id, w1.created_at FROM wallets w1 JOIN wallets w2 ON w1.user_id = w2.user_id WHERE w1.created_at < '2024-01-01' AND w2.created_at >= '2024-01-01' GROUP BY w1.wallet_id, w1.user_id, w1.created_at;

[User] For these users, show their user ID, the creation date of their earliest wallet created *before* '2024-01-01', and the creation date of their latest wallet created *on or after* '2024-01-01'.

[Assistant] SELECT user_id, MIN(CASE WHEN created_at < '2024-01-01' THEN created_at ELSE NULL END) AS earliest_before_2024, MAX(CASE WHEN created_at >= '2024-01-01' THEN created_at ELSE NULL END) AS latest_from_2024 FROM wallets GROUP BY user_id HAVING MIN(CASE WHEN created_at < '2024-01-01' THEN created_at ELSE NULL END) IS NOT NULL AND MAX(CASE WHEN created_at >= '2024-01-01' THEN created_at ELSE NULL END) IS NOT NULL;

[User] How many such users are there?

[Assistant] SELECT COUNT(DISTINCT user_id) FROM ( SELECT user_id FROM wallets WHERE created_at < '2024-01-01' GROUP BY user_id ) t1 JOIN ( SELECT user_id FROM wallets WHERE created_at >= '2024-01-01' GROUP BY user_id ) t2 ON t1.user_id = t2.user_id;

[User] For each user, show their user ID and the count of unique wallet addresses they own.

[Assistant] SELECT user_id, COUNT(DISTINCT address) FROM wallets GROUP BY user_id;

[User] List pairs of wallets created on the same day but belonging to different users. Show the wallet IDs, user IDs, and creation dates for both wallets in each pair.

[Assistant] SELECT w1.wallet_id AS wallet1_id, w1.user_id AS user1_id, w1.created_at AS wallet1_created_at, w2.wallet_id AS wallet2_id, w2.user_id AS user2_id, w2.created_at AS wallet2_created_at FROM wallets w1 JOIN wallets w2 ON DATE(w1.created_at) = DATE(w2.created_at) AND w1.user_id != w2.user_id AND w1.wallet_id < w2.wallet_id;

[User] Filter the previous results to only include pairs where both wallet addresses start with '0x'.

[Assistant] SELECT w1.wallet_id AS wallet1_id, w1.user_id AS user1_id, w1.created_at AS wallet1_created_at, w2.wallet_id AS wallet2_id, w2.user_id AS user2_id, w2.created_at AS wallet2_created_at FROM wallets w1 JOIN wallets w2 ON DATE(w1.created_at) = DATE(w2.created_at) AND w1.user_id != w2.user_id AND w1.wallet_id < w2.wallet_id WHERE w1.address LIKE '0x%' AND w2.address LIKE '0x%';

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

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

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

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


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE trading_platform.kyc_audit (
    kyc_audit_id character varying(64) NOT NULL,  -- unique identifier for the KYC audit
    user_id character varying(64) NOT NULL, -- identifier of the user being audited
    status character varying(32) NOT NULL, -- status of the KYC audit (e.g., pending, approved, rejected)
    reviewed_at timestamp NOT NULL, -- time when the KYC audit was reviewed
    PRIMARY KEY (kyc_audit_id)
)

[User] Show me all KYC audit records for user ID 'user_abc_123'.

[Assistant] SELECT kyc_audit_id, user_id, status, reviewed_at FROM kyc_audit WHERE user_id = 'user_abc_123';

[User] From those, list only the ones with status 'pending'.

[Assistant] SELECT kyc_audit_id, user_id, status, reviewed_at FROM kyc_audit WHERE user_id = 'user_abc_123' AND status = 'pending';

[User] Order the results by the review date in ascending order.

[Assistant] SELECT kyc_audit_id, user_id, status, reviewed_at FROM kyc_audit WHERE user_id = 'user_abc_123' AND status = 'pending' ORDER BY reviewed_at ASC;

[User] Just show the latest pending audit for that user, displaying the user_id, status, and reviewed_at date.

[Assistant] SELECT user_id, status, reviewed_at FROM kyc_audit WHERE user_id = 'user_abc_123' AND status = 'pending' ORDER BY reviewed_at DESC LIMIT 1;

[User] Show me the top 5 users with the most KYC audits, along with their latest audit status.

[Assistant] SELECT user_id, status, COUNT(*) as audit_count FROM trading_platform.kyc_audit GROUP BY user_id, status ORDER BY audit_count DESC LIMIT 5;

[User] Now modify the query to show only users whose latest KYC status was rejected.

[Assistant] WITH latest_audit AS (SELECT user_id, status, ROW_NUMBER() OVER (PARTITION BY user_id ORDER BY reviewed_at DESC) as rn FROM trading_platform.kyc_audit) SELECT user_id, status FROM latest_audit WHERE rn = 1 AND status = 'rejected' LIMIT 5;

[User] Actually, I want to see the count of rejected audits per user instead of just the latest status.

[Assistant] SELECT user_id, COUNT(*) as rejected_count FROM trading_platform.kyc_audit WHERE status = 'rejected' GROUP BY user_id ORDER BY rejected_count DESC LIMIT 5;

[User] List all users who have had their KYC status changed from 'approved' to 'rejected', along with the timestamps of both audits.

[Assistant] SELECT a.user_id, a.reviewed_at AS approved_time, r.reviewed_at AS rejected_time FROM trading_platform.kyc_audit a JOIN trading_platform.kyc_audit r ON a.user_id = r.user_id WHERE a.status = 'approved' AND r.status = 'rejected' AND a.reviewed_at < r.reviewed_at AND NOT EXISTS (SELECT 1 FROM trading_platform.kyc_audit x WHERE x.user_id = a.user_id AND x.reviewed_at > a.reviewed_at AND x.reviewed_at < r.reviewed_at);

[User] Now modify the query to only include cases where the status change happened within 30 days.

[Assistant] SELECT a.user_id, a.reviewed_at AS approved_time, r.reviewed_at AS rejected_time FROM trading_platform.kyc_audit a JOIN trading_platform.kyc_audit r ON a.user_id = r.user_id WHERE a.status = 'approved' AND r.status = 'rejected' AND a.reviewed_at < r.reviewed_at AND r.reviewed_at <= a.reviewed_at + INTERVAL '30 days' AND NOT EXISTS (SELECT 1 FROM trading_platform.kyc_audit x WHERE x.user_id = a.user_id AND x.reviewed_at > a.reviewed_at AND x.reviewed_at < r.reviewed_at);

[User] Can you also include the users' email addresses and calculate the number of days between approval and rejection?

[Assistant] SELECT a.user_id, u.email, a.reviewed_at AS approved_time, r.reviewed_at AS rejected_time, EXTRACT(DAY FROM (r.reviewed_at - a.reviewed_at)) AS days_between FROM trading_platform.kyc_audit a JOIN trading_platform.kyc_audit r ON a.user_id = r.user_id JOIN trading_platform.users u ON a.user_id = u.user_id WHERE a.status = 'approved' AND r.status = 'rejected' AND a.reviewed_at < r.reviewed_at AND r.reviewed_at <= a.reviewed_at + INTERVAL '30 days' AND NOT EXISTS (SELECT 1 FROM trading_platform.kyc_audit x WHERE x.user_id = a.user_id AND x.reviewed_at > a.reviewed_at AND x.reviewed_at < r.reviewed_at);

[User] Show assets of type 'token', including their name, symbol, and any associated metadata key and value.

[Assistant] SELECT t1.name, t1.symbol, t2.key, t2.value FROM trading_platform.assets AS t1 LEFT JOIN trading_platform.metadata AS t2 ON t1.asset_id = t2.asset_id WHERE t1.type = 'token';

[User] For the results from the previous query, only include metadata entries where the key is 'website'.

[Assistant] SELECT t1.name, t1.symbol, t2.key, t2.value FROM trading_platform.assets AS t1 LEFT JOIN trading_platform.metadata AS t2 ON t1.asset_id = t2.asset_id WHERE t1.type = 'token' AND t2.key = 'website';

[User] Instead of listing metadata, count how many assets of type 'token' have a metadata entry with key 'website'.

[Assistant] SELECT COUNT(DISTINCT t1.asset_id) FROM trading_platform.assets AS t1 INNER JOIN trading_platform.metadata AS t2 ON t1.asset_id = t2.asset_id WHERE t1.type = 'token' AND t2.key = 'website';

[User] Also, provide the total count of assets with type 'token'.

[Assistant] SELECT COUNT(DISTINCT t1.asset_id) FILTER (WHERE t2.key = 'website') AS token_with_website_metadata_count, COUNT(DISTINCT t1.asset_id) AS total_token_count FROM trading_platform.assets AS t1 LEFT JOIN trading_platform.metadata AS t2 ON t1.asset_id = t2.asset_id WHERE t1.type = 'token';

[User] Count the number of assets for each asset type.

[Assistant] SELECT type, COUNT(*) FROM trading_platform.assets GROUP BY type;

[User] Show me all users who had their KYC rejected along with when their review was completed.

[Assistant] SELECT user_id, reviewed_at FROM trading_platform.kyc_audit WHERE status = 'rejected';

[User] List the names of all DApps whose description contains the word 'auction' along with the user IDs of anyone who has had a KYC audit.

[Assistant]
SELECT d.name AS dapp_name, k.user_id
FROM trading_platform.dapps d
JOIN trading_platform.kyc_audit k ON 1=1
WHERE d.description ILIKE '%auction%'
ORDER BY d.name, k.user_id;

[User] Just show KYC audits with a status that is not 'approved'.

[Assistant]
SELECT d.name AS dapp_name, k.user_id, k.status
FROM trading_platform.dapps d
JOIN trading_platform.kyc_audit k ON 1=1
WHERE d.description ILIKE '%auction%'
  AND k.status <> 'approved'
ORDER BY d.name, k.user_id;

[User] Actually, I want to include the reviewed_at time for each audit result too.

[Assistant]
SELECT d.name AS dapp_name, k.user_id, k.status, k.reviewed_at
FROM trading_platform.dapps d
JOIN trading_platform.kyc_audit k ON 1=1
WHERE d.description ILIKE '%auction%'
  AND k.status <> 'approved'
ORDER BY d.name, k.user_id, k.reviewed_at;

[User] Filter further to only show audits reviewed after January 1, 2024.

[Assistant]
SELECT d.name AS dapp_name, k.user_id, k.status, k.reviewed_at
FROM trading_platform.dapps d
JOIN trading_platform.kyc_audit k ON 1=1
WHERE d.description ILIKE '%auction%'
  AND k.status <> 'approved'
  AND k.reviewed_at > '2024-01-01'
ORDER BY d.name, k.user_id, k.reviewed_at;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE 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 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 nft_holder_historical ( block_number bigint NOT NULL, contract_address varchar NOT NULL, wallet_address varchar NOT NULL, token_id varchar NOT NULL, contract_type varchar NOT NULL, amount varchar NOT NULL, pk integer NOT NULL )
CREATE TABLE 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 nft_collections ( blockchain varchar NOT NULL, contract_address varchar NOT NULL, name varchar NOT NULL, symbol varchar NOT NULL, deploy_block_number bigint NOT NULL, deploy_block_time bigint NOT NULL, erc_type varchar NOT NULL, owner varchar NOT NULL, traits varchar NOT NULL, description varchar NOT NULL, slug varchar NOT NULL, media_info varchar NOT NULL, image_url varchar NOT NULL, banner_image_url varchar NOT NULL, updated_at bigint NOT NULL, banner varchar NOT NULL, token_count bigint NOT NULL, floor_price varchar NOT NULL, floor_price_symbol varchar NOT NULL, floor_price_contract varchar NOT NULL, pk integer NOT NULL )
CREATE TABLE token_prices ( uuid 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_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_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_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 token IDs and names of all NFTs minted by the wallet '0x1234...' on Ethereum.

[Assistant] SELECT token_id, name FROM nft_metadata WHERE minter = '0x1234...' AND blockchain = 'Ethereum';

[User] Now, for each of those NFTs, show also the collection name by joining to nft_collections.

[Assistant] SELECT nm.token_id, nm.name, nc.name AS collection_name FROM nft_metadata nm LEFT JOIN nft_collections nc ON nm.contract_address = nc.contract_address AND nc.blockchain = 'Ethereum' WHERE nm.minter = '0x1234...' AND nm.blockchain = 'Ethereum';

[User] Only include NFTs where the rarity rank is below 100.

[Assistant] SELECT nm.token_id, nm.name, nc.name AS collection_name FROM nft_metadata nm LEFT JOIN nft_collections nc ON nm.contract_address = nc.contract_address AND nc.blockchain = 'Ethereum' WHERE nm.minter = '0x1234...' AND nm.blockchain = 'Ethereum' AND nm.rarity_rank < 100;

[User] Show me all ERC20 tokens (from token_metas) with a total supply over 1,000,000, including their contract address and symbol.

[Assistant] SELECT contract_address, symbol FROM token_metas WHERE is_erc20 = 1 AND CAST(total_supply AS FLOAT) > 1000000;

[User] Please also give me the name and decimals for each token.

[Assistant] SELECT contract_address, symbol, name, decimals FROM token_metas WHERE is_erc20 = 1 AND CAST(total_supply AS FLOAT) > 1000000;

[User] Add the latest price for each token by joining with token_prices_latest.

[Assistant] SELECT tm.contract_address, tm.symbol, tm.name, tm.decimals, tpl.price FROM token_metas tm LEFT JOIN token_prices_latest tpl ON tm.contract_address = tpl.address AND tm.symbol = tpl.symbol WHERE tm.is_erc20 = 1 AND CAST(tm.total_supply AS FLOAT) > 1000000;

[User] I'm interested only in tokens where the price is over $0.5.

[Assistant] SELECT tm.contract_address, tm.symbol, tm.name, tm.decimals, tpl.price FROM token_metas tm LEFT JOIN token_prices_latest tpl ON tm.contract_address = tpl.address AND tm.symbol = tpl.symbol WHERE tm.is_erc20 = 1 AND CAST(tm.total_supply AS FLOAT) > 1000000 AND tpl.price > 0.5;

[User] For all NFT collections on the Ethereum blockchain, show me the collection name and the current floor price. Sort by floor price descending.

[Assistant] SELECT name, floor_price FROM nft_collections WHERE blockchain = 'Ethereum' ORDER BY CAST(floor_price AS FLOAT) DESC;

[User] Include also the collection symbol and the number of tokens in each collection.

[Assistant] SELECT name, symbol, floor_price, token_count FROM nft_collections WHERE blockchain = 'Ethereum' ORDER BY CAST(floor_price AS FLOAT) DESC;

[User] Can you also show the owner of each collection in the result?

[Assistant] SELECT name, symbol, floor_price, token_count, owner FROM nft_collections WHERE blockchain = 'Ethereum' ORDER BY CAST(floor_price AS FLOAT) DESC;

[User] Now only include collections whose floor price is greater than 1 ETH.

[Assistant] SELECT name, symbol, floor_price, token_count, owner FROM nft_collections WHERE blockchain = 'Ethereum' AND CAST(floor_price AS FLOAT) > 1 AND floor_price_symbol = 'ETH' ORDER BY CAST(floor_price AS FLOAT) DESC;

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

[Assistant] SELECT eb.wallet_address, tm.symbol, eb.amount FROM erc20_balances eb JOIN token_metas tm ON eb.contract_address = tm.contract_address WHERE CAST(eb.amount AS decimal) > 1000;

[User] Can you join this with the token_prices_latest table to include the current price of each token and sort by amount in descending order?

[Assistant] SELECT eb.wallet_address, tm.symbol, eb.amount, tpl.price FROM erc20_balances eb JOIN token_metas tm ON eb.contract_address = tm.contract_address JOIN token_prices_latest tpl ON tm.contract_address = tpl.address WHERE CAST(eb.amount AS decimal) > 1000 ORDER BY CAST(eb.amount AS decimal) DESC;

[User] Show me the object ID, coin type, and balance for all SUI coins where the status is 'active'.

[Assistant] SELECT object_id, coin_type, balance FROM sui_coins WHERE status = 'active'

[User] Also, include the owner address in the result.

[Assistant] SELECT object_id, coin_type, balance, owner FROM sui_coins WHERE status = 'active'

[User] Filter the results to only show coins where the balance is greater than '100000000000'.

[Assistant] SELECT object_id, coin_type, balance, owner FROM sui_coins WHERE status = 'active' AND CAST(balance AS NUMERIC) > 100000000000

[User] Sort the results by balance in descending order and limit the output to 10.

[Assistant] SELECT object_id, coin_type, balance, owner FROM sui_coins WHERE status = 'active' AND CAST(balance AS NUMERIC) > 100000000000 ORDER BY CAST(balance AS NUMERIC) DESC LIMIT 10

[User] Find the contract address and name for all NFT collections listed on the 'Ethereum' blockchain.

[Assistant] SELECT contract_address, name FROM nft_collections WHERE blockchain = 'Ethereum'

[User] For these collections, can you show the count of unique wallet addresses holding NFTs in each collection by joining with nft_holders?

[Assistant] SELECT T1.contract_address, T1.name, COUNT(DISTINCT T2.wallet_address) AS unique_holder_count FROM nft_collections AS T1 JOIN nft_holders AS T2 ON T1.contract_address = T2.contract_address WHERE T1.blockchain = 'Ethereum' GROUP BY T1.contract_address, T1.name

[User] Please filter the results to only include collections that have more than 100 unique holders.

[Assistant] SELECT T1.contract_address, T1.name, COUNT(DISTINCT T2.wallet_address) AS unique_holder_count FROM nft_collections AS T1 JOIN nft_holders AS T2 ON T1.contract_address = T2.contract_address WHERE T1.blockchain = 'Ethereum' GROUP BY T1.contract_address, T1.name HAVING COUNT(DISTINCT T2.wallet_address) > 100

[User] List all ERC20 token symbols and their latest prices for tokens where the total supply is greater than '100000000000000000000'.

[Assistant] SELECT T1.symbol, T2.price FROM token_metas AS T1 JOIN token_prices_latest AS T2 ON T1.contract_address = T2.address WHERE T1.is_erc20 = 1 AND CAST(T1.total_supply AS NUMERIC) > 100000000000000000000

[User] Can you also include the token name and decimals in the result?

[Assistant] SELECT T1.symbol, T1.name, T1.decimals, T2.price FROM token_metas AS T1 JOIN token_prices_latest AS T2 ON T1.contract_address = T2.address WHERE T1.is_erc20 = 1 AND CAST(T1.total_supply AS NUMERIC) > 100000000000000000000

[User] Now, only show tokens where the latest price is above 100.

[Assistant] SELECT T1.symbol, T1.name, T1.decimals, T2.price FROM token_metas AS T1 JOIN token_prices_latest AS T2 ON T1.contract_address = T2.address WHERE T1.is_erc20 = 1 AND CAST(T1.total_supply AS NUMERIC) > 100000000000000000000 AND T2.price > 100

[User] Finally, sort the results by price descending and limit to the top 10.

[Assistant] SELECT T1.symbol, T1.name, T1.decimals, T2.price FROM token_metas AS T1 JOIN token_prices_latest AS T2 ON T1.contract_address = T2.address WHERE T1.is_erc20 = 1 AND CAST(T1.total_supply AS NUMERIC) > 100000000000000000000 AND T2.price > 100 ORDER BY T2.price DESC LIMIT 10


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE government_services.citizens ( citizen_id character varying(64) NOT NULL, national_id_number character varying(128) NOT NULL UNIQUE, first_name character varying(100) NOT NULL, last_name character varying(100) NOT NULL, date_of_birth date NOT NULL, gender character varying(20), primary_address text NOT NULL, contact_email character varying(128) UNIQUE, contact_phone character varying(32), registration_date timestamp NOT NULL, is_verified boolean DEFAULT false, PRIMARY KEY (citizen_id) )
CREATE TABLE government_services.agencies ( agency_id character varying(64) NOT NULL, agency_name character varying(255) NOT NULL, jurisdiction_level character varying(50) NOT NULL, primary_contact_email character varying(128), main_phone_number character varying(32), website_url character varying(255), established_date date, parent_agency_id character varying(64), PRIMARY KEY (agency_id) )
CREATE TABLE government_services.services ( service_id character varying(64) NOT NULL, agency_id character varying(64) NOT NULL, service_name character varying(255) NOT NULL, description text, category character varying(100), eligibility_criteria text, standard_fee numeric(10, 2) DEFAULT 0.00, average_processing_time_days integer, is_active boolean DEFAULT true, online_application_url character varying(255), PRIMARY KEY (service_id) )
CREATE TABLE government_services.applications ( application_id character varying(64) NOT NULL, citizen_id character varying(64) NOT NULL, service_id character varying(64) NOT NULL, submitted_at timestamp NOT NULL, status character varying(50) NOT NULL, last_updated_at timestamp NOT NULL, assigned_employee_id character varying(64), decision_date date, notes text, reference_number character varying(100) UNIQUE, PRIMARY KEY (application_id) )
CREATE TABLE government_services.payments ( payment_id character varying(64) NOT NULL, application_id character varying(64), citizen_id character varying(64) NOT NULL, service_id character varying(64), amount numeric(12, 2) NOT NULL, currency character varying(3) NOT NULL DEFAULT 'USD', payment_method character varying(50), payment_provider_reference character varying(128), payment_timestamp timestamp NOT NULL, status character varying(30) NOT NULL, notes text, PRIMARY KEY (payment_id) )
CREATE TABLE government_services.employees ( employee_id character varying(64) NOT NULL, agency_id character varying(64) NOT NULL, first_name character varying(100) NOT NULL, last_name character varying(100) NOT NULL, job_title character varying(150) NOT NULL, department character varying(100), work_email character varying(128) NOT NULL UNIQUE, work_phone character varying(32), hire_date date NOT NULL, termination_date date, access_level character varying(50), manager_employee_id character varying(64), PRIMARY KEY (employee_id) )
CREATE TABLE government_services.service_locations ( location_id character varying(64) NOT NULL, agency_id character varying(64) NOT NULL, location_name character varying(200), address text NOT NULL, city character varying(100), state character varying(50), postal_code character varying(20), latitude numeric(9, 6), longitude numeric(9, 6), operating_hours text, contact_phone character varying(32), is_accessible boolean, PRIMARY KEY (location_id) )
CREATE TABLE government_services.appointments ( appointment_id character varying(64) NOT NULL, citizen_id character varying(64) NOT NULL, employee_id character varying(64), location_id character varying(64), service_id character varying(64), scheduled_start_time timestamp NOT NULL, scheduled_end_time timestamp, purpose text NOT NULL, status character varying(30) NOT NULL, booking_method character varying(50), created_at timestamp NOT NULL, notes text, PRIMARY KEY (appointment_id) )
CREATE TABLE government_services.notifications ( notification_id character varying(64) NOT NULL, citizen_id character varying(64) NOT NULL, application_id character varying(64), message_subject character varying(255), message_body text NOT NULL, channel character varying(30) NOT NULL, sent_at timestamp NOT NULL, status character varying(30) NOT NULL, related_entity_type character varying(50), related_entity_id character varying(64), PRIMARY KEY (notification_id) )

[User] List the first and last names of citizens along with the reference numbers of the applications they have submitted.

[Assistant] SELECT T1.first_name ,  T1.last_name ,  T2.reference_number FROM government_services.citizens AS T1 JOIN government_services.applications AS T2 ON T1.citizen_id  =  T2.citizen_id

[User] List the names of active services offered by agencies with at least one accessible service location in the state of 'New York'. Show the service name, category, agency name, and the location name.

[Assistant] SELECT T1.service_name, T1.category, T2.agency_name, T3.location_name FROM government_services.services AS T1 JOIN government_services.agencies AS T2 ON T1.agency_id = T2.agency_id JOIN government_services.service_locations AS T3 ON T2.agency_id = T3.agency_id WHERE T1.is_active IS TRUE AND T3.is_accessible IS TRUE AND T3.state = 'New York';

[User] How many employees are currently not terminated?

[Assistant] SELECT COUNT(*) FROM government_services.employees WHERE termination_date IS NULL;

[User] Retrieve each employee's first and last name along with the count of applications they've been assigned that are currently in the 'Under Review' status.

[Assistant]
SELECT e.first_name,
       e.last_name,
       COUNT(app.application_id) AS under_review_count
FROM government_services.employees e
LEFT JOIN government_services.applications app ON e.employee_id = app.assigned_employee_id
    AND app.status = 'Under Review'
GROUP BY e.employee_id, e.first_name, e.last_name;

[User] List the names of agencies and their established dates, but only for agencies that offer at least one service.

[Assistant] SELECT DISTINCT T1.agency_name ,  T1.established_date FROM government_services.agencies AS T1 JOIN government_services.services AS T2 ON T1.agency_id  =  T2.agency_id

[User] For each service location in Texas, provide the location name, city, and the number of appointments scheduled there by verified citizens.

[Assistant]
SELECT sl.location_name, sl.city, COUNT(a.appointment_id) AS appointment_count
FROM government_services.service_locations sl
JOIN government_services.appointments a ON sl.location_id = a.location_id
JOIN government_services.citizens c ON a.citizen_id = c.citizen_id AND c.is_verified = TRUE
WHERE sl.state = 'Texas'
GROUP BY sl.location_id, sl.location_name, sl.city;

[User] List each employee's first and last name along with the count of active services offered by their agency.

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

[User] Actually, only include employees whose service count is greater than 5.

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


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE transportation.routes ( route_id text PRIMARY KEY, route_number text, description text, origin_location_id text, destination_location_id text, distance_km numeric, estimated_duration_minutes int, type text )
CREATE TABLE transportation.trips ( trip_id text PRIMARY KEY, route_id text, vehicle_id text, driver_id text, scheduled_departure timestamp, actual_departure timestamp, scheduled_arrival timestamp, actual_arrival timestamp, origin_location_id text, destination_location_id text, status text, passenger_count int, cargo_manifest_id text )
CREATE TABLE transportation.maintenance_logs ( log_id text PRIMARY KEY, vehicle_id text, service_date date, odometer_reading int, service_type text, description text, cost numeric, mechanic_name text, next_service_due_date date )
CREATE TABLE transportation.passengers ( passenger_id text PRIMARY KEY, first_name text, last_name text, email text, phone_number text, date_of_birth date, loyalty_program_id text, created_at timestamp )
CREATE TABLE transportation.bookings ( booking_id text PRIMARY KEY, passenger_id text, trip_id text, seat_number text, booking_time timestamp, status text, fare numeric, payment_transaction_id text, special_requests text )

[User] Show each passenger's name and the total number of trips they have booked.

[Assistant]
SELECT p.first_name, p.last_name, COUNT(b.booking_id) AS trip_count
FROM transportation.passengers p
JOIN transportation.bookings b ON p.passenger_id = b.passenger_id
GROUP BY p.passenger_id, p.first_name, p.last_name;

[User] Can you show only those passengers who have booked more than two trips?

[Assistant]
SELECT p.first_name, p.last_name, COUNT(b.booking_id) AS trip_count
FROM transportation.passengers p
JOIN transportation.bookings b ON p.passenger_id = b.passenger_id
GROUP BY p.passenger_id, p.first_name, p.last_name
HAVING COUNT(b.booking_id) > 2;

[User] Now, for these passengers, also display their email addresses.

[Assistant]
SELECT p.first_name, p.last_name, p.email, COUNT(b.booking_id) AS trip_count
FROM transportation.passengers p
JOIN transportation.bookings b ON p.passenger_id = b.passenger_id
GROUP BY p.passenger_id, p.first_name, p.last_name, p.email
HAVING COUNT(b.booking_id) > 2;

[User] Show me the trip_id, route_number, and scheduled_departure for all trips where the associated vehicle has a maintenance log indicating the next service is due before 2024-05-01.

[Assistant]
SELECT t.trip_id, r.route_number, t.scheduled_departure
FROM transportation.trips t
JOIN transportation.routes r ON t.route_id = r.route_id
JOIN transportation.maintenance_logs m ON t.vehicle_id = m.vehicle_id
WHERE m.next_service_due_date < '2024-05-01';

[User] For the above list, also include the mechanic_name from the maintenance log.

[Assistant]
SELECT t.trip_id, r.route_number, t.scheduled_departure, m.mechanic_name
FROM transportation.trips t
JOIN transportation.routes r ON t.route_id = r.route_id
JOIN transportation.maintenance_logs m ON t.vehicle_id = m.vehicle_id
WHERE m.next_service_due_date < '2024-05-01';

[User] Show all maintenance logs with the vehicle ID, service date, service type, and the name and city of the location where the vehicle's most recent fueling occurred.

[Assistant]
SELECT ml.log_id, ml.vehicle_id, ml.service_date, ml.service_type, loc.name AS last_fuel_location_name, loc.city AS last_fuel_location_city
FROM transportation.maintenance_logs ml
LEFT JOIN (
    SELECT fl.vehicle_id, fl.location_id, fl.log_timestamp
    FROM transportation.fuel_logs fl
    INNER JOIN (
        SELECT vehicle_id, MAX(log_timestamp) AS max_log_timestamp
        FROM transportation.fuel_logs
        GROUP BY vehicle_id
    ) latest ON fl.vehicle_id = latest.vehicle_id AND fl.log_timestamp = latest.max_log_timestamp
) last_fl ON ml.vehicle_id = last_fl.vehicle_id
LEFT JOIN transportation.locations loc ON last_fl.location_id = loc.location_id;

[User] I want to see only maintenance logs where the service_type is 'Inspection' and the maintenance cost exceeds 150.

[Assistant]
SELECT ml.log_id, ml.vehicle_id, ml.service_date, ml.service_type, loc.name AS last_fuel_location_name, loc.city AS last_fuel_location_city
FROM transportation.maintenance_logs ml
LEFT JOIN (
    SELECT fl.vehicle_id, fl.location_id, fl.log_timestamp
    FROM transportation.fuel_logs fl
    INNER JOIN (
        SELECT vehicle_id, MAX(log_timestamp) AS max_log_timestamp
        FROM transportation.fuel_logs
        GROUP BY vehicle_id
    ) latest ON fl.vehicle_id = latest.vehicle_id AND fl.log_timestamp = latest.max_log_timestamp
) last_fl ON ml.vehicle_id = last_fl.vehicle_id
LEFT JOIN transportation.locations loc ON last_fl.location_id = loc.location_id
WHERE ml.service_type = 'Inspection' AND ml.cost > 150;

[User] Can you also add the odometer reading from the maintenance log and sort the results by service_date descending?

[Assistant]
SELECT ml.log_id, ml.vehicle_id, ml.service_date, ml.service_type, ml.odometer_reading, loc.name AS last_fuel_location_name, loc.city AS last_fuel_location_city
FROM transportation.maintenance_logs ml
LEFT JOIN (
    SELECT fl.vehicle_id, fl.location_id, fl.log_timestamp
    FROM transportation.fuel_logs fl
    INNER JOIN (
        SELECT vehicle_id, MAX(log_timestamp) AS max_log_timestamp
        FROM transportation.fuel_logs
        GROUP BY vehicle_id
    ) latest ON fl.vehicle_id = latest.vehicle_id AND fl.log_timestamp = latest.max_log_timestamp
) last_fl ON ml.vehicle_id = last_fl.vehicle_id
LEFT JOIN transportation.locations loc ON last_fl.location_id = loc.location_id
WHERE ml.service_type = 'Inspection' AND ml.cost > 150
ORDER BY ml.service_date DESC;

[User] Sorry, can you restrict the results to logs from after January 1, 2023?

[Assistant]
SELECT ml.log_id, ml.vehicle_id, ml.service_date, ml.service_type, ml.odometer_reading, loc.name AS last_fuel_location_name, loc.city AS last_fuel_location_city
FROM transportation.maintenance_logs ml
LEFT JOIN (
    SELECT fl.vehicle_id, fl.location_id, fl.log_timestamp
    FROM transportation.fuel_logs fl
    INNER JOIN (
        SELECT vehicle_id, MAX(log_timestamp) AS max_log_timestamp
        FROM transportation.fuel_logs
        GROUP BY vehicle_id
    ) latest ON fl.vehicle_id = latest.vehicle_id AND fl.log_timestamp = latest.max_log_timestamp
) last_fl ON ml.vehicle_id = last_fl.vehicle_id
LEFT JOIN transportation.locations loc ON last_fl.location_id = loc.location_id
WHERE ml.service_type = 'Inspection' AND ml.cost > 150 AND ml.service_date > '2023-01-01'
ORDER BY ml.service_date DESC;

[User] For each city, show how many trips have started there (origin), how many have ended there (destination), and the total number of unique vehicles used in trips that started in that city.

[Assistant]
SELECT l.city,
       COUNT(CASE WHEN t.origin_location_id = l.location_id THEN 1 END) AS trips_started,
       COUNT(CASE WHEN t.destination_location_id = l.location_id THEN 1 END) AS trips_ended,
       COUNT(DISTINCT CASE WHEN t.origin_location_id = l.location_id THEN t.vehicle_id END) AS unique_vehicles_started
FROM transportation.locations l
LEFT JOIN transportation.trips t ON t.origin_location_id = l.location_id OR t.destination_location_id = l.location_id
GROUP BY l.city;

[User] Show me the driver_id and full name for all drivers.

[Assistant] SELECT driver_id, first_name, last_name FROM transportation.drivers;

[User] Only show drivers whose status is 'Inactive'.

[Assistant] SELECT driver_id, first_name, last_name FROM transportation.drivers WHERE status = 'Inactive';

[User] Can you also include their hire date and sort by hire date descending?

[Assistant] SELECT driver_id, first_name, last_name, hire_date FROM transportation.drivers WHERE status = 'Inactive' ORDER BY hire_date DESC;

[User] How many inactive drivers were hired before 2022?

[Assistant] SELECT COUNT(*) FROM transportation.drivers WHERE status = 'Inactive' AND hire_date < '2022-01-01';

[User] What is the average maintenance cost per service_type for maintenance performed in 2023?

[Assistant]
SELECT service_type, AVG(cost) AS avg_cost
FROM transportation.maintenance_logs
WHERE service_date BETWEEN '2023-01-01' AND '2023-12-31'
GROUP BY service_type;

[User] Now include only those service types where the average cost exceeds 500 and sort by avg_cost desc.

[Assistant]
SELECT service_type, AVG(cost) AS avg_cost
FROM transportation.maintenance_logs
WHERE service_date BETWEEN '2023-01-01' AND '2023-12-31'
GROUP BY service_type
HAVING AVG(cost) > 500
ORDER BY avg_cost DESC;

[User] List each vehicle's ID, make, and model along with the count of trips scheduled to depart in the next 7 days.

[Assistant]
SELECT v.vehicle_id, v.make, v.model, COUNT(t.trip_id) AS trip_count
FROM transportation.vehicles v
JOIN transportation.trips t
  ON v.vehicle_id = t.vehicle_id
WHERE t.scheduled_departure BETWEEN NOW() AND NOW() + INTERVAL '7 days'
GROUP BY v.vehicle_id, v.make, v.model;

[User] Now filter to only include vehicles with more than 2 upcoming trips and order by trip_count descending.

[Assistant]
SELECT v.vehicle_id, v.make, v.model, COUNT(t.trip_id) AS trip_count
FROM transportation.vehicles v
JOIN transportation.trips t
  ON v.vehicle_id = t.vehicle_id
WHERE t.scheduled_departure BETWEEN NOW() AND NOW() + INTERVAL '7 days'
GROUP BY v.vehicle_id, v.make, v.model
HAVING COUNT(t.trip_id) > 2
ORDER BY trip_count DESC;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE legal_services.time_entries ( entry_id text PRIMARY KEY, case_id text, lawyer_id text, date_worked date, hours_spent numeric, billing_rate numeric, description text, is_billable bool, is_billed bool, invoice_id text, created_at timestamp )

[User] List all time entries that do not have a description, including the entry ID, date worked, hours spent, and the first and last name of the lawyer who recorded the entry.

[Assistant] SELECT te.entry_id, te.date_worked, te.hours_spent, l.first_name, l.last_name FROM legal_services.time_entries AS te JOIN legal_services.lawyers AS l ON te.lawyer_id = l.lawyer_id WHERE te.description IS NULL OR te.description = '';

[User] Show me the total hours spent by each lawyer on a specific case, say with case_id = 'CASE001'.

[Assistant] SELECT lawyer_id, SUM(hours_spent) AS total_hours FROM legal_services.time_entries WHERE case_id = 'CASE001' GROUP BY lawyer_id;

[User] Can you also include only the entries that are billable?

[Assistant] SELECT lawyer_id, SUM(hours_spent) AS total_hours FROM legal_services.time_entries WHERE case_id = 'CASE001' AND is_billable = TRUE GROUP BY lawyer_id;

[User] Now, show only those lawyers who have logged more than 5 billable hours on this case.

[Assistant] SELECT lawyer_id, SUM(hours_spent) AS total_hours FROM legal_services.time_entries WHERE case_id = 'CASE001' AND is_billable = TRUE GROUP BY lawyer_id HAVING SUM(hours_spent) > 5;

[User] How many time entries were recorded on each date? List the date and the count of entries for that date, ordered by date.

[Assistant] SELECT date_worked, COUNT(*) AS entry_count FROM legal_services.time_entries GROUP BY date_worked ORDER BY date_worked;

[User] List each case_id along with the total hours worked and total billed amount for that case.

[Assistant] SELECT case_id, SUM(hours_spent) AS total_hours, SUM(hours_spent * billing_rate) AS total_billed_amount FROM legal_services.time_entries GROUP BY case_id;

[User] Only include entries that have been billed.

[Assistant] SELECT case_id, SUM(hours_spent) AS total_hours, SUM(hours_spent * billing_rate) AS total_billed_amount FROM legal_services.time_entries WHERE is_billed = TRUE GROUP BY case_id;

[User] And restrict to cases worked on in February 2024 only.

[Assistant] SELECT case_id, SUM(hours_spent) AS total_hours, SUM(hours_spent * billing_rate) AS total_billed_amount FROM legal_services.time_entries WHERE is_billed = TRUE AND date_worked >= '2024-02-01' AND date_worked < '2024-03-01' GROUP BY case_id;

[User] Please order the results by total_billed_amount descending.

[Assistant] SELECT case_id, SUM(hours_spent) AS total_hours, SUM(hours_spent * billing_rate) AS total_billed_amount FROM legal_services.time_entries WHERE is_billed = TRUE AND date_worked >= '2024-02-01' AND date_worked < '2024-03-01' GROUP BY case_id ORDER BY total_billed_amount DESC;

[User] Show the invoice_id and total hours logged for each invoice.

[Assistant] SELECT invoice_id, SUM(hours_spent) AS total_hours FROM legal_services.time_entries WHERE invoice_id IS NOT NULL GROUP BY invoice_id;

[User] Only include invoices with more than 10 total hours.

[Assistant] SELECT invoice_id, SUM(hours_spent) AS total_hours FROM legal_services.time_entries WHERE invoice_id IS NOT NULL GROUP BY invoice_id HAVING SUM(hours_spent) > 10;

[User] Show me all time entries for case ID 'case_abc', including the entry ID, date worked, hours spent, and the first and last name of the lawyer.

[Assistant] SELECT te.entry_id, te.date_worked, te.hours_spent, l.first_name, l.last_name FROM legal_services.time_entries AS te JOIN legal_services.lawyers AS l ON te.lawyer_id = l.lawyer_id WHERE te.case_id = 'case_abc';

[User] Okay, now only show the entries that are marked as billable.

[Assistant] SELECT te.entry_id, te.date_worked, te.hours_spent, l.first_name, l.last_name FROM legal_services.time_entries AS te JOIN legal_services.lawyers AS l ON te.lawyer_id = l.lawyer_id WHERE te.case_id = 'case_abc' AND te.is_billable = TRUE;

[User] Also, include the description for these entries and sort them by date worked, oldest first.

[Assistant] SELECT te.entry_id, te.date_worked, te.hours_spent, l.first_name, l.last_name, te.description FROM legal_services.time_entries AS te JOIN legal_services.lawyers AS l ON te.lawyer_id = l.lawyer_id WHERE te.case_id = 'case_abc' AND te.is_billable = TRUE ORDER BY te.date_worked ASC;

[User] List total billable hours and total amount per lawyer for July 2023.

[Assistant]
SELECT lawyer_id,
       SUM(hours_spent) AS total_hours,
       SUM(hours_spent * billing_rate) AS total_amount
FROM legal_services.time_entries
WHERE is_billable = TRUE
  AND date_worked BETWEEN '2023-07-01' AND '2023-07-31'
GROUP BY lawyer_id;

[User] Actually, only include lawyers who logged more than 40 billable hours that month.

[Assistant]
SELECT lawyer_id,
       SUM(hours_spent) AS total_hours,
       SUM(hours_spent * billing_rate) AS total_amount
FROM legal_services.time_entries
WHERE is_billable = TRUE
  AND date_worked BETWEEN '2023-07-01' AND '2023-07-31'
GROUP BY lawyer_id
HAVING SUM(hours_spent) > 40;

[User] Also show the average billing rate for each of those lawyers.

[Assistant]
SELECT lawyer_id,
       SUM(hours_spent) AS total_hours,
       SUM(hours_spent * billing_rate) AS total_amount,
       AVG(billing_rate) AS avg_rate
FROM legal_services.time_entries
WHERE is_billable = TRUE
  AND date_worked BETWEEN '2023-07-01' AND '2023-07-31'
GROUP BY lawyer_id
HAVING SUM(hours_spent) > 40;

[User] Finally, order the results by total_amount descending.

[Assistant]
SELECT lawyer_id,
       SUM(hours_spent) AS total_hours,
       SUM(hours_spent * billing_rate) AS total_amount,
       AVG(billing_rate) AS avg_rate
FROM legal_services.time_entries
WHERE is_billable = TRUE
  AND date_worked BETWEEN '2023-07-01' AND '2023-07-31'
GROUP BY lawyer_id
HAVING SUM(hours_spent) > 40
ORDER BY total_amount DESC;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE legal_services.documents (
    document_id character varying(64) NOT NULL,  -- unique identifier for the document
    case_id character varying(64) NOT NULL, -- FK to cases table
    document_name character varying(255) NOT NULL, -- name of the document file
    document_type character varying(100), -- e.g., Pleading, Contract, Evidence, Correspondence
    storage_path text NOT NULL, -- path or reference to the document storage location
    uploaded_by_lawyer_id character varying(64), -- FK to lawyers table (who uploaded it)
    upload_timestamp timestamp NOT NULL, -- time the document was uploaded
    version integer DEFAULT 1, -- document version number
    description text, -- brief description or notes about the document
    PRIMARY KEY (document_id)
)

[User] Find pairs of documents in the same case where one document is version 1 and the other is the highest version for that document_name, showing case_id, document_name, version1, latest_version, version1_upload_timestamp, and latest_upload_timestamp.

[Assistant]
SELECT d1.case_id,
       d1.document_name,
       d1.version AS version1,
       d2.version AS latest_version,
       d1.upload_timestamp AS version1_upload_timestamp,
       d2.upload_timestamp AS latest_upload_timestamp
FROM legal_services.documents d1
JOIN (
    SELECT case_id, document_name, MAX(version) AS max_version
    FROM legal_services.documents
    GROUP BY case_id, document_name
) lv ON d1.case_id = lv.case_id
     AND d1.document_name = lv.document_name
     AND d1.version = 1
JOIN legal_services.documents d2
  ON d2.case_id = lv.case_id
     AND d2.document_name = lv.document_name
     AND d2.version = lv.max_version;

[User] Actually, I only want the pairs where the difference between latest_version and version1 is at least 2.

[Assistant]
SELECT d1.case_id,
       d1.document_name,
       d1.version AS version1,
       d2.version AS latest_version,
       d1.upload_timestamp AS version1_upload_timestamp,
       d2.upload_timestamp AS latest_upload_timestamp
FROM legal_services.documents d1
JOIN (
    SELECT case_id, document_name, MAX(version) AS max_version
    FROM legal_services.documents
    GROUP BY case_id, document_name
) lv ON d1.case_id = lv.case_id
     AND d1.document_name = lv.document_name
     AND d1.version = 1
JOIN legal_services.documents d2
  ON d2.case_id = lv.case_id
     AND d2.document_name = lv.document_name
     AND d2.version = lv.max_version
WHERE (d2.version - d1.version) >= 2;

[User] Also include the uploaded_by_lawyer_id for both the version1 and the latest version documents.

[Assistant]
SELECT d1.case_id,
       d1.document_name,
       d1.version AS version1,
       d2.version AS latest_version,
       d1.upload_timestamp AS version1_upload_timestamp,
       d2.upload_timestamp AS latest_upload_timestamp,
       d1.uploaded_by_lawyer_id AS version1_uploaded_by,
       d2.uploaded_by_lawyer_id AS latest_uploaded_by
FROM legal_services.documents d1
JOIN (
    SELECT case_id, document_name, MAX(version) AS max_version
    FROM legal_services.documents
    GROUP BY case_id, document_name
) lv ON d1.case_id = lv.case_id
     AND d1.document_name = lv.document_name
     AND d1.version = 1
JOIN legal_services.documents d2
  ON d2.case_id = lv.case_id
     AND d2.document_name = lv.document_name
     AND d2.version = lv.max_version
WHERE (d2.version - d1.version) >= 2;

[User] List document names and versions for documents that share the same case_id, showing each pair of versions.

[Assistant] SELECT d1.case_id, d1.document_name AS doc_name_v1, d1.version AS version1, d2.document_name AS doc_name_v2, d2.version AS version2 FROM legal_services.documents d1 JOIN legal_services.documents d2 ON d1.case_id = d2.case_id AND d1.version < d2.version;

[User] Actually, I only want to compare the highest version against the second highest version per case.

[Assistant] SELECT d_prev.case_id, d_prev.document_name AS prev_doc, d_prev.version AS prev_version, d_latest.document_name AS latest_doc, d_latest.version AS latest_version FROM legal_services.documents d_latest JOIN legal_services.documents d_prev ON d_latest.case_id = d_prev.case_id AND d_prev.version = d_latest.version - 1 WHERE d_latest.version = (SELECT MAX(version) FROM legal_services.documents d WHERE d.case_id = d_latest.case_id);

[User] Also include the upload timestamps and restrict to cases with at least three versions.

[Assistant] SELECT d_latest.case_id, d_prev.document_name AS prev_doc, d_prev.upload_timestamp AS prev_upload, d_latest.document_name AS latest_doc, d_latest.upload_timestamp AS latest_upload FROM legal_services.documents d_latest JOIN legal_services.documents d_prev ON d_latest.case_id = d_prev.case_id AND d_prev.version = d_latest.version - 1 WHERE d_latest.version = (SELECT MAX(version) FROM legal_services.documents d WHERE d.case_id = d_latest.case_id) AND (SELECT COUNT(*) FROM legal_services.documents d2 WHERE d2.case_id = d_latest.case_id) >= 3;

[User] List pairs of documents uploaded by the same lawyer, showing uploader ID and both document names.

[Assistant] SELECT d1.uploaded_by_lawyer_id, d1.document_name AS doc1, d2.document_name AS doc2 FROM legal_services.documents d1 JOIN legal_services.documents d2 ON d1.uploaded_by_lawyer_id = d2.uploaded_by_lawyer_id AND d1.document_id < d2.document_id;

[User] Only include pairs where the upload timestamps are within 7 days of each other.

[Assistant] SELECT d1.uploaded_by_lawyer_id, d1.document_name AS doc1, d2.document_name AS doc2 FROM legal_services.documents d1 JOIN legal_services.documents d2 ON d1.uploaded_by_lawyer_id = d2.uploaded_by_lawyer_id AND d1.document_id < d2.document_id AND ABS(EXTRACT(EPOCH FROM (d1.upload_timestamp - d2.upload_timestamp)))/86400 <= 7;

[User] Show me document names and upload timestamps for documents linked to cases that were opened after January 1, 2023.

[Assistant] SELECT T1.document_name, T1.upload_timestamp FROM documents AS T1 JOIN cases AS T2 ON T1.case_id = T2.case_id WHERE T2.date_opened > '2023-01-01';

[User] Additionally, only include documents that have a version number greater than 1.

[Assistant] SELECT T1.document_name, T1.upload_timestamp FROM documents AS T1 JOIN cases AS T2 ON T1.case_id = T2.case_id WHERE T2.date_opened > '2023-01-01' AND T1.version > 1;

[User] List the document name, type, version, and description for all documents.

[Assistant] SELECT document_name, document_type, version, description FROM documents;

[User] Only include documents where the description is not null.

[Assistant] SELECT document_name, document_type, version, description FROM documents WHERE description IS NOT NULL;

[User] Also, filter to only show documents with a version greater than 2.

[Assistant] SELECT document_name, document_type, version, description FROM documents WHERE description IS NOT NULL AND version > 2;

[User] Order the results by upload timestamp descending.

[Assistant] SELECT document_name, document_type, version, description FROM documents WHERE description IS NOT NULL AND version > 2 ORDER BY upload_timestamp DESC;

[User] List the names of law firms whose managing partner has uploaded at least one document, and show the managing partner ID along with the firm's phone number.

[Assistant] SELECT DISTINCT T1.firm_name, T1.managing_partner_id, T1.phone FROM legal_services.law_firms AS T1 JOIN legal_services.documents AS T2 ON T1.managing_partner_id = T2.uploaded_by_lawyer_id;

[User] List all cases that have an invoice issued in July 2024, showing the case name, case number, invoice number, and issue date.

[Assistant] SELECT T1.case_name, T1.case_number, T2.invoice_number, T2.issue_date FROM legal_services.cases AS T1 JOIN legal_services.invoices AS T2 ON T1.case_id = T2.case_id WHERE T2.issue_date BETWEEN '2024-07-01' AND '2024-07-31';


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE transportation.locations (
    location_id character varying(64) NOT NULL,  -- unique identifier for the location
    name character varying(255) NOT NULL, -- name of the location (e.g., Central Station, Depot Alpha, Pier 7)
    type character varying(64) NOT NULL, -- e.g., Station, Stop, Depot, Port, Airport, Customer Address
    address_line1 character varying(255), -- street address
    city character varying(128), -- city name
    state_province character varying(128), -- state or province
    postal_code character varying(32), -- postal code
    country character varying(64) NOT NULL, -- country name
    latitude numeric(9, 6), -- geographic latitude
    longitude numeric(9, 6), -- geographic longitude
    timezone character varying(64), -- IANA timezone name (e.g., America/New_York)
    PRIMARY KEY (location_id)
)

[User] List all pairs of locations within the same state_province where the two locations are of different types. For each pair, show the first location's name, type, city, and the second location's name, type, city, and their shared state_province.

[Assistant]
SELECT l1.name AS name1, l1.type AS type1, l1.city AS city1, l2.name AS name2, l2.type AS type2, l2.city AS city2, l1.state_province
FROM transportation.locations l1
JOIN transportation.locations l2
  ON l1.state_province = l2.state_province
 AND l1.location_id < l2.location_id
 AND l1.type <> l2.type;

[User] Now restrict the results to only include pairs where both locations are in the city of 'Houston'.

[Assistant]
SELECT l1.name AS name1, l1.type AS type1, l1.city AS city1, l2.name AS name2, l2.type AS type2, l2.city AS city2, l1.state_province
FROM transportation.locations l1
JOIN transportation.locations l2
  ON l1.state_province = l2.state_province
 AND l1.city = 'Houston'
 AND l2.city = 'Houston'
 AND l1.location_id < l2.location_id
 AND l1.type <> l2.type;

[User] Which locations lack a postal code? For each, display the name, type, city, and state_province.

[Assistant]
SELECT name, type, city, state_province
FROM transportation.locations
WHERE postal_code IS NULL;

[User] Also show the country and order the results by city in ascending order.

[Assistant]
SELECT name, type, city, state_province, country
FROM transportation.locations
WHERE postal_code IS NULL
ORDER BY city ASC;

[User] List for each fuel_type and unit the average total_cost at each fueling location. Include fuel_type, unit, location name, city, and average_cost, and order the result by average_cost descending.

[Assistant]
SELECT
    f.fuel_type,
    f.unit,
    l.name AS location_name,
    l.city,
    AVG(f.total_cost) AS average_cost
FROM
    transportation.fuel_logs f
JOIN
    transportation.locations l
  ON f.location_id = l.location_id
GROUP BY
    f.fuel_type,
    f.unit,
    l.name,
    l.city
ORDER BY
    average_cost DESC;

[User] I need a report showing the number of maintenance services performed per vehicle, broken down by service_type.

[Assistant]
SELECT
    vehicle_id,
    service_type,
    COUNT(*) AS service_count
FROM
    transportation.maintenance_logs
GROUP BY
    vehicle_id,
    service_type;

[User] Actually, filter to include only vehicles that have at least 2 "Oil Change" services.

[Assistant]
SELECT
    vehicle_id,
    service_type,
    COUNT(*) AS service_count
FROM
    transportation.maintenance_logs
GROUP BY
    vehicle_id,
    service_type
HAVING
    service_type = 'Oil Change'
    AND COUNT(*) >= 2;

[User] Now also include only those vehicles whose average cost for "Engine Repair" exceeds 500.

[Assistant]
SELECT
    m.vehicle_id,
    COUNT(*) FILTER (WHERE m.service_type = 'Oil Change') AS oil_change_count,
    AVG(m.cost) FILTER (WHERE m.service_type = 'Engine Repair') AS avg_engine_repair_cost
FROM
    transportation.maintenance_logs m
GROUP BY
    m.vehicle_id
HAVING
    COUNT(*) FILTER (WHERE m.service_type = 'Oil Change') >= 2
    AND AVG(m.cost) FILTER (WHERE m.service_type = 'Engine Repair') > 500;

[User] Finally, sort by total services performed descending and limit to the top 5 vehicles.

[Assistant]
SELECT
    m.vehicle_id,
    COUNT(*) AS total_services,
    COUNT(*) FILTER (WHERE m.service_type = 'Oil Change') AS oil_change_count,
    AVG(m.cost) FILTER (WHERE m.service_type = 'Engine Repair') AS avg_engine_repair_cost
FROM
    transportation.maintenance_logs m
GROUP BY
    m.vehicle_id
HAVING
    COUNT(*) FILTER (WHERE m.service_type = 'Oil Change') >= 2
    AND AVG(m.cost) FILTER (WHERE m.service_type = 'Engine Repair') > 500
ORDER BY
    total_services DESC
LIMIT 5;

[User] For each passenger, show their full name and the total amount they have spent on completed bookings.

[Assistant]
SELECT p.first_name, p.last_name, SUM(b.fare) AS total_spent
FROM transportation.passengers p
JOIN transportation.bookings b ON p.passenger_id = b.passenger_id
WHERE b.status = 'Completed'
GROUP BY p.passenger_id, p.first_name, p.last_name;

[User] Can you also include the number of completed bookings for each passenger?

[Assistant]
SELECT p.first_name, p.last_name, COUNT(b.booking_id) AS completed_bookings, SUM(b.fare) AS total_spent
FROM transportation.passengers p
JOIN transportation.bookings b ON p.passenger_id = b.passenger_id
WHERE b.status = 'Completed'
GROUP BY p.passenger_id, p.first_name, p.last_name;

[User] Only include passengers who have spent more than 300 in total.

[Assistant]
SELECT p.first_name, p.last_name, COUNT(b.booking_id) AS completed_bookings, SUM(b.fare) AS total_spent
FROM transportation.passengers p
JOIN transportation.bookings b ON p.passenger_id = b.passenger_id
WHERE b.status = 'Completed'
GROUP BY p.passenger_id, p.first_name, p.last_name
HAVING SUM(b.fare) > 300;

[User] I got an error about missing the email, please add their email to the output.

[Assistant]
SELECT p.first_name, p.last_name, p.email, COUNT(b.booking_id) AS completed_bookings, SUM(b.fare) AS total_spent
FROM transportation.passengers p
JOIN transportation.bookings b ON p.passenger_id = b.passenger_id
WHERE b.status = 'Completed'
GROUP BY p.passenger_id, p.first_name, p.last_name, p.email
HAVING SUM(b.fare) > 300;

[User] Get all pairs of locations in the same city, showing both location IDs, names, and the shared city.

[Assistant]
SELECT l1.location_id AS location1_id, l1.name AS location1_name,
       l2.location_id AS location2_id, l2.name AS location2_name,
       l1.city
FROM transportation.locations l1
JOIN transportation.locations l2
  ON l1.city = l2.city
 AND l1.location_id < l2.location_id;

[User] Show all locations in 'Texas' with their name, city, and type.

[Assistant]
SELECT location_id, name, city, type
FROM transportation.locations
WHERE state_province = 'Texas';

[User] Actually, only include locations in 'Houston' city.

[Assistant]
SELECT location_id, name, city, type
FROM transportation.locations
WHERE state_province = 'Texas'
  AND city = 'Houston';

[User] I want to also see their postal codes.

[Assistant]
SELECT location_id, name, city, type, postal_code
FROM transportation.locations
WHERE state_province = 'Texas'
  AND city = 'Houston';

[User] Please order the results by name in ascending order.

[Assistant]
SELECT location_id, name, city, type, postal_code
FROM transportation.locations
WHERE state_province = 'Texas'
  AND city = 'Houston'
ORDER BY name ASC;