System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE social_media.hashtags ( hashtag_id character varying(64) NOT NULL, tag_name character varying(100) NOT NULL UNIQUE, created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, PRIMARY KEY (hashtag_id) )

[User] List all pairs of hashtags created on the same calendar date, showing both tag names and the creation date.

[Assistant]
SELECT h1.tag_name AS tag1, h2.tag_name AS tag2, DATE(h1.created_at) AS created_date
FROM social_media.hashtags h1
JOIN social_media.hashtags h2
  ON DATE(h1.created_at) = DATE(h2.created_at)
  AND h1.hashtag_id <> h2.hashtag_id;

[User] Also, only include each pair once by enforcing the first tag_name to be alphabetically before the second.

[Assistant]
SELECT h1.tag_name AS tag1, h2.tag_name AS tag2, DATE(h1.created_at) AS created_date
FROM social_media.hashtags h1
JOIN social_media.hashtags h2
  ON DATE(h1.created_at) = DATE(h2.created_at)
  AND h1.tag_name < h2.tag_name;

[User] How many hashtags were created in each month of 2024?

[Assistant]
SELECT date_trunc('month', created_at) AS month, COUNT(*) AS count
FROM social_media.hashtags
WHERE created_at >= '2024-01-01'
  AND created_at < '2025-01-01'
GROUP BY month
ORDER BY month;

[User] List all pairs of hashtags that were created on the same date. Show both tag names and the creation date.

[Assistant]
SELECT a.tag_name AS tag1, b.tag_name AS tag2, a.created_at::date AS created_date
FROM social_media.hashtags a
JOIN social_media.hashtags b
  ON a.created_at::date = b.created_at::date
  AND a.hashtag_id < b.hashtag_id;

[User] Actually, only include pairs where both tag names start with the letter 'S'.

[Assistant]
SELECT a.tag_name AS tag1, b.tag_name AS tag2, a.created_at::date AS created_date
FROM social_media.hashtags a
JOIN social_media.hashtags b
  ON a.created_at::date = b.created_at::date
  AND a.hashtag_id < b.hashtag_id
WHERE a.tag_name LIKE 'S%'
  AND b.tag_name LIKE 'S%';

[User] Count the total number of hashtags.

[Assistant] SELECT COUNT(*) FROM social_media.hashtags;

[User] Show me the hashtag IDs and their names.

[Assistant] SELECT hashtag_id, tag_name FROM social_media.hashtags;

[User] I also want to see when each hashtag was created.

[Assistant] SELECT hashtag_id, tag_name, created_at FROM social_media.hashtags;

[User] Filter the list to only show hashtags whose name starts with the letter 'S'.

[Assistant] SELECT hashtag_id, tag_name, created_at FROM social_media.hashtags WHERE tag_name LIKE 'S%';

[User] I need all pairs of hashtags that start with the same first two letters. Show both tag names.

[Assistant]
SELECT h1.tag_name AS tag1, h2.tag_name AS tag2
FROM social_media.hashtags h1
JOIN social_media.hashtags h2
  ON LEFT(h1.tag_name, 2) = LEFT(h2.tag_name, 2)
  AND h1.hashtag_id <> h2.hashtag_id;

[User] Please filter these pairs to include only those created in the same year.

[Assistant]
SELECT h1.tag_name AS tag1, h2.tag_name AS tag2
FROM social_media.hashtags h1
JOIN social_media.hashtags h2
  ON LEFT(h1.tag_name, 2) = LEFT(h2.tag_name, 2)
  AND EXTRACT(YEAR FROM h1.created_at) = EXTRACT(YEAR FROM h2.created_at)
  AND h1.hashtag_id <> h2.hashtag_id;

[User] Now also include the year in the output.

[Assistant]
SELECT h1.tag_name AS tag1, h2.tag_name AS tag2, EXTRACT(YEAR FROM h1.created_at) AS year
FROM social_media.hashtags h1
JOIN social_media.hashtags h2
  ON LEFT(h1.tag_name, 2) = LEFT(h2.tag_name, 2)
  AND EXTRACT(YEAR FROM h1.created_at) = EXTRACT(YEAR FROM h2.created_at)
  AND h1.hashtag_id <> h2.hashtag_id;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE social_media.posts ( post_id.text, user_id.text, content.text, media_url.text, media_type.text, created_at.timestamp, updated_at.timestamp, visibility.text, location_lat.numeric, location_lon.numeric )
CREATE TABLE social_media.likes ( like_id.text, user_id.text, post_id.text, comment_id.text, created_at.timestamp )
CREATE TABLE social_media.hashtags ( hashtag_id text, tag_name text, created_at timestamp )
CREATE TABLE social_media.post_hashtags ( post_hashtag_id text, post_id text, hashtag_id text )
CREATE TABLE social_media.conversation_participants ( participant_id character varying(64) NOT NULL, conversation_id character varying(64) NOT NULL, user_id character varying(64) NOT NULL, joined_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, last_read_at timestamp, PRIMARY KEY (participant_id), CONSTRAINT unique_user_conversation UNIQUE (conversation_id, user_id) )
CREATE TABLE social_media.notifications (
    notification_id character varying(64) NOT NULL, -- unique identifier for the notification
    recipient_user_id character varying(64) NOT NULL, -- user receiving the notification (FK to users.user_id)
    sender_user_id character varying(64), -- user triggering the notification (FK to users.user_id, can be null for system notifications)
    notification_type character varying(30) NOT NULL, -- type of notification ('like', 'comment', 'follow', 'mention', 'message')
    target_entity_id character varying(64), -- ID of the related entity (post_id, comment_id, user_id, conversation_id)
    target_entity_type character varying(20), -- type of the related entity ('post', 'comment', 'user', 'conversation')
    created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, -- timestamp notification was created
    read_at timestamp, -- timestamp notification was marked as read
    PRIMARY KEY (notification_id)
)

[User] List all post IDs and the corresponding hashtag names where posts were created near latitude 40.0 and longitude -74.0.

[Assistant]
SELECT p.post_id, h.tag_name
FROM social_media.posts p
JOIN social_media.post_hashtags ph ON p.post_id = ph.post_id
JOIN social_media.hashtags h ON ph.hashtag_id = h.hashtag_id
WHERE ABS(p.location_lat - 40.0) < 0.1 AND ABS(p.location_lon + 74.0) < 0.1;

[User] Only show the results where the hashtag name contains the word 'event'.

[Assistant]
SELECT p.post_id, h.tag_name
FROM social_media.posts p
JOIN social_media.post_hashtags ph ON p.post_id = ph.post_id
JOIN social_media.hashtags h ON ph.hashtag_id = h.hashtag_id
WHERE ABS(p.location_lat - 40.0) < 0.1 AND ABS(p.location_lon + 74.0) < 0.1
  AND h.tag_name ILIKE '%event%';

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

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

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

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

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

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

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

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

[User] List group conversation names and the IDs of notifications associated with them, where the notification type is 'mention'.

[Assistant] SELECT T1.group_name, T2.notification_id FROM social_media.conversations AS T1 INNER JOIN social_media.notifications AS T2 ON T1.conversation_id = T2.target_entity_id WHERE T1.is_group_chat = TRUE AND T2.notification_type = 'mention';

[User] Only include notifications that have not been read (read_at is null).

[Assistant] SELECT T1.group_name, T2.notification_id FROM social_media.conversations AS T1 INNER JOIN social_media.notifications AS T2 ON T1.conversation_id = T2.target_entity_id WHERE T1.is_group_chat = TRUE AND T2.notification_type = 'mention' AND T2.read_at IS NULL;

[User] List all notifications related to messages. Please show notification_id, recipient_user_id, conversation_id, and the creation time.

[Assistant]
SELECT notification_id, recipient_user_id, target_entity_id AS conversation_id, created_at
FROM social_media.notifications
WHERE notification_type = 'message' AND target_entity_type = 'conversation';

[User] Actually, please only include notifications that haven't been read yet.

[Assistant]
SELECT notification_id, recipient_user_id, target_entity_id AS conversation_id, created_at
FROM social_media.notifications
WHERE notification_type = 'message' AND target_entity_type = 'conversation' AND read_at IS NULL;

[User] Could you also show the sender_user_id for each notification?

[Assistant]
SELECT notification_id, recipient_user_id, sender_user_id, target_entity_id AS conversation_id, created_at
FROM social_media.notifications
WHERE notification_type = 'message' AND target_entity_type = 'conversation' AND read_at IS NULL;

[User] List all users with private profiles who have disabled push notifications, including their user_id and email_notifications_enabled status.

[Assistant]
SELECT user_id,
       email_notifications_enabled
FROM social_media.user_settings
WHERE private_profile = true
  AND push_notifications_enabled = false;

[User] I want to see for each group chat the count of unread 'mention' notifications received by its recipients. Include conversation_id, group_name, and unread_mentions.

[Assistant]
SELECT c.conversation_id,
       c.group_name,
       COUNT(n.notification_id) AS unread_mentions
FROM social_media.conversations c
JOIN social_media.notifications n
  ON n.target_entity_type = 'conversation'
  AND n.target_entity_id = c.conversation_id
  AND c.is_group_chat = true
  AND n.notification_type = 'mention'
  AND n.read_at IS NULL
GROUP BY c.conversation_id, c.group_name;

[User] Now only include group chats created within the past year.

[Assistant]
SELECT c.conversation_id,
       c.group_name,
       COUNT(n.notification_id) AS unread_mentions
FROM social_media.conversations c
JOIN social_media.notifications n
  ON n.target_entity_type = 'conversation'
  AND n.target_entity_id = c.conversation_id
  AND c.is_group_chat = true
  AND n.notification_type = 'mention'
  AND n.read_at IS NULL
WHERE c.created_at >= NOW() - INTERVAL '1 year'
GROUP BY c.conversation_id, c.group_name;

[User] Order the results by unread_mentions descending.

[Assistant]
SELECT c.conversation_id,
       c.group_name,
       COUNT(n.notification_id) AS unread_mentions
FROM social_media.conversations c
JOIN social_media.notifications n
  ON n.target_entity_type = 'conversation'
  AND n.target_entity_id = c.conversation_id
  AND c.is_group_chat = true
  AND n.notification_type = 'mention'
  AND n.read_at IS NULL
WHERE c.created_at >= NOW() - INTERVAL '1 year'
GROUP BY c.conversation_id, c.group_name
ORDER BY unread_mentions DESC;

[User] Limit to the top 5 group chats.

[Assistant]
SELECT c.conversation_id,
       c.group_name,
       COUNT(n.notification_id) AS unread_mentions
FROM social_media.conversations c
JOIN social_media.notifications n
  ON n.target_entity_type = 'conversation'
  AND n.target_entity_id = c.conversation_id
  AND c.is_group_chat = true
  AND n.notification_type = 'mention'
  AND n.read_at IS NULL
WHERE c.created_at >= NOW() - INTERVAL '1 year'
GROUP BY c.conversation_id, c.group_name
ORDER BY unread_mentions DESC
LIMIT 5;


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

[User] Please list the full name and status of clients who have not provided a company name.

[Assistant]
SELECT first_name, last_name, status
FROM legal_services.clients
WHERE company_name IS NULL;

[User] Can you show me the company name, email, and phone of all clients who share the same status?

[Assistant]
SELECT a.company_name, a.email, a.phone, a.status
FROM legal_services.clients a
JOIN legal_services.clients b ON a.status = b.status AND a.client_id <> b.client_id;

[User] What if I only want to see those clients who registered before January 1st, 2023?

[Assistant]
SELECT a.company_name, a.email, a.phone, a.status
FROM legal_services.clients a
JOIN legal_services.clients b ON a.status = b.status AND a.client_id <> b.client_id
WHERE a.date_registered < '2023-01-01';

[User] Please add each client's first and last name, and sort the results by company_name.

[Assistant]
SELECT a.first_name, a.last_name, a.company_name, a.email, a.phone, a.status
FROM legal_services.clients a
JOIN legal_services.clients b ON a.status = b.status AND a.client_id <> b.client_id
WHERE a.date_registered < '2023-01-01'
ORDER BY a.company_name;

[User] I need a list of unique company names and the number of clients in each company.

[Assistant]
SELECT company_name, COUNT(*) AS client_count
FROM legal_services.clients
WHERE company_name IS NOT NULL
GROUP BY company_name;

[User] Only include companies where there are at least 2 clients.

[Assistant]
SELECT company_name, COUNT(*) AS client_count
FROM legal_services.clients
WHERE company_name IS NOT NULL
GROUP BY company_name
HAVING COUNT(*) >= 2;

[User] Also, show the email addresses of the clients in those companies.

[Assistant]
SELECT c.company_name, c.email
FROM legal_services.clients c
WHERE c.company_name IN (
  SELECT company_name
  FROM legal_services.clients
  WHERE company_name IS NOT NULL
  GROUP BY company_name
  HAVING COUNT(*) >= 2
)
ORDER BY c.company_name, c.email;

[User] Only show companies whose name contains the word 'Group'.

[Assistant]
SELECT c.company_name, c.email
FROM legal_services.clients c
WHERE c.company_name IN (
  SELECT company_name
  FROM legal_services.clients
  WHERE company_name IS NOT NULL AND company_name ILIKE '%Group%'
  GROUP BY company_name
  HAVING COUNT(*) >= 2
)
ORDER BY c.company_name, c.email;

[User] List all pairs of clients who registered in the same year. Show each client's first_name, last_name, and the registration year.

[Assistant] SELECT c1.first_name AS first_name_1, c1.last_name AS last_name_1, c2.first_name AS first_name_2, c2.last_name AS last_name_2, EXTRACT(YEAR FROM c1.date_registered) AS registration_year FROM legal_services.clients c1 JOIN legal_services.clients c2 ON EXTRACT(YEAR FROM c1.date_registered) = EXTRACT(YEAR FROM c2.date_registered) AND c1.client_id < c2.client_id;

[User] Actually, only include clients with status = 'active'.

[Assistant] SELECT c1.first_name AS first_name_1, c1.last_name AS last_name_1, c2.first_name AS first_name_2, c2.last_name AS last_name_2, EXTRACT(YEAR FROM c1.date_registered) AS registration_year FROM legal_services.clients c1 JOIN legal_services.clients c2 ON EXTRACT(YEAR FROM c1.date_registered) = EXTRACT(YEAR FROM c2.date_registered) AND c1.client_id < c2.client_id WHERE c1.status = 'active' AND c2.status = 'active';

[User] Also, sort the results by registration_year descending and then by the first client's last_name ascending.

[Assistant] SELECT c1.first_name AS first_name_1, c1.last_name AS last_name_1, c2.first_name AS first_name_2, c2.last_name AS last_name_2, EXTRACT(YEAR FROM c1.date_registered) AS registration_year FROM legal_services.clients c1 JOIN legal_services.clients c2 ON EXTRACT(YEAR FROM c1.date_registered) = EXTRACT(YEAR FROM c2.date_registered) AND c1.client_id < c2.client_id WHERE c1.status = 'active' AND c2.status = 'active' ORDER BY registration_year DESC, last_name_1 ASC;

[User] List the first_name, last_name, and email of all clients whose email domain is 'gmail.com'.

[Assistant] SELECT first_name, last_name, email FROM legal_services.clients WHERE SUBSTRING(email FROM POSITION('@' IN email) + 1) = 'gmail.com';

[User] List all pairs of clients who registered on the same day, showing each client's first_name, last_name, and the registration date.

[Assistant] SELECT c1.first_name AS first_name_1, c1.last_name AS last_name_1, c2.first_name AS first_name_2, c2.last_name AS last_name_2, DATE(c1.date_registered) AS registration_date FROM legal_services.clients c1 JOIN legal_services.clients c2 ON DATE(c1.date_registered) = DATE(c2.date_registered) AND c1.client_id < c2.client_id;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE financial_services.securities ( security_id text PRIMARY KEY, ticker_symbol text, isin_code text, cusip_code text, security_name text, security_type text, exchange text, currency text, issuer_name text, sector text, last_updated timestamp )

[User] I want to list each security alongside another security issued by the same issuer.

[Assistant]
SELECT a.security_id, a.ticker_symbol, b.security_id AS other_security_id, b.ticker_symbol AS other_ticker, a.issuer_name
FROM financial_services.securities a
JOIN financial_services.securities b ON a.issuer_name = b.issuer_name AND a.security_id <> b.security_id;

[User] Only include cases where the issuer has issued more than one security.

[Assistant]
SELECT a.security_id, a.ticker_symbol, b.security_id AS other_security_id, b.ticker_symbol AS other_ticker, a.issuer_name
FROM financial_services.securities a
JOIN financial_services.securities b ON a.issuer_name = b.issuer_name AND a.security_id <> b.security_id
WHERE a.issuer_name IN (
  SELECT issuer_name
  FROM financial_services.securities
  GROUP BY issuer_name
  HAVING COUNT(*) > 1
);

[User] Sort the result by issuer_name, then by a.ticker_symbol.

[Assistant]
SELECT a.security_id, a.ticker_symbol, b.security_id AS other_security_id, b.ticker_symbol AS other_ticker, a.issuer_name
FROM financial_services.securities a
JOIN financial_services.securities b ON a.issuer_name = b.issuer_name AND a.security_id <> b.security_id
WHERE a.issuer_name IN (
  SELECT issuer_name
  FROM financial_services.securities
  GROUP BY issuer_name
  HAVING COUNT(*) > 1
)
ORDER BY a.issuer_name, a.ticker_symbol;

[User] What is the count of securities for each security_type in the 'Technology' sector?

[Assistant] SELECT security_type, COUNT(*) as count FROM financial_services.securities WHERE sector = 'Technology' GROUP BY security_type;

[User] List all securities (security_id, ticker_symbol, security_name) that have a currency of 'EUR' and were last updated within the last 30 days, along with their exchange and sector information.

[Assistant] SELECT security_id, ticker_symbol, security_name, exchange, sector FROM financial_services.securities WHERE currency = 'EUR' AND last_updated >= CURRENT_DATE - INTERVAL '30 days';

[User] Can you provide a summary of how many securities exist for each combination of exchange and sector?

[Assistant]
SELECT exchange, sector, COUNT(*) AS total_count
FROM financial_services.securities
GROUP BY exchange, sector;

[User] Please exclude any records where sector is NULL.

[Assistant]
SELECT exchange, sector, COUNT(*) AS total_count
FROM financial_services.securities
WHERE sector IS NOT NULL
GROUP BY exchange, sector;

[User] Finally, sort the output by total_count in descending order.

[Assistant]
SELECT exchange, sector, COUNT(*) AS total_count
FROM financial_services.securities
WHERE sector IS NOT NULL
GROUP BY exchange, sector
ORDER BY total_count DESC;

[User] List all securities issued by 'Morgan Stanley' along with their ticker_symbol, security_name, and exchange. Then also show the sector for each.

[Assistant] SELECT ticker_symbol, security_name, exchange, sector FROM financial_services.securities WHERE issuer_name = 'Morgan Stanley';

[User] Only include those securities that are traded on the NASDAQ exchange.

[Assistant] SELECT ticker_symbol, security_name, exchange, sector FROM financial_services.securities WHERE issuer_name = 'Morgan Stanley' AND exchange = 'NASDAQ';

[User] Add another filter: the security_type must be 'Equity'.

[Assistant] SELECT ticker_symbol, security_name, exchange, sector FROM financial_services.securities WHERE issuer_name = 'Morgan Stanley' AND exchange = 'NASDAQ' AND security_type = 'Equity';

[User] Finally, sort the results by ticker_symbol in ascending order.

[Assistant] SELECT ticker_symbol, security_name, exchange, sector FROM financial_services.securities WHERE issuer_name = 'Morgan Stanley' AND exchange = 'NASDAQ' AND security_type = 'Equity' ORDER BY ticker_symbol ASC;

[User] I’d like to find all pairs of securities that belong to the same sector.

[Assistant]
SELECT a.security_id, a.ticker_symbol, b.security_id AS pair_security_id, b.ticker_symbol AS pair_ticker_symbol, a.sector
FROM financial_services.securities a
JOIN financial_services.securities b ON a.sector = b.sector
WHERE a.security_id < b.security_id;

[User] Actually, only include pairs where the two securities are listed on different exchanges.

[Assistant]
SELECT a.security_id, a.ticker_symbol, a.exchange AS exchange_a, b.security_id AS pair_security_id, b.ticker_symbol AS pair_ticker_symbol, b.exchange AS exchange_b, a.sector
FROM financial_services.securities a
JOIN financial_services.securities b ON a.sector = b.sector AND a.security_id < b.security_id
WHERE a.exchange <> b.exchange;

[User] Also, I want the results sorted by sector, then by exchange_a.

[Assistant]
SELECT a.security_id, a.ticker_symbol, a.exchange AS exchange_a, b.security_id AS pair_security_id, b.ticker_symbol AS pair_ticker_symbol, b.exchange AS exchange_b, a.sector
FROM financial_services.securities a
JOIN financial_services.securities b ON a.sector = b.sector AND a.security_id < b.security_id
WHERE a.exchange <> b.exchange
ORDER BY a.sector, a.exchange;

[User] One more thing: include both exchanges in the ORDER BY so that within each sector it’s sorted by exchange_a then exchange_b.

[Assistant]
SELECT a.security_id, a.ticker_symbol, a.exchange AS exchange_a, b.security_id AS pair_security_id, b.ticker_symbol AS pair_ticker_symbol, b.exchange AS exchange_b, a.sector
FROM financial_services.securities a
JOIN financial_services.securities b ON a.sector = b.sector AND a.security_id < b.security_id
WHERE a.exchange <> b.exchange
ORDER BY a.sector, a.exchange, b.exchange;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE transportation.routes ( route_id character varying(64) NOT NULL, route_number character varying(32) NOT NULL UNIQUE, description text, origin_location_id character varying(64) NOT NULL, destination_location_id character varying(64) NOT NULL, distance_km numeric(10, 2), estimated_duration_minutes integer, type character varying(32) NOT NULL, PRIMARY KEY (route_id) )
CREATE TABLE transportation.trips ( trip_id character varying(64) NOT NULL, route_id character varying(64), vehicle_id character varying(64) NOT NULL, driver_id character varying(64) NOT NULL, scheduled_departure timestamp with time zone NOT NULL, actual_departure timestamp with time zone, scheduled_arrival timestamp with time zone NOT NULL, actual_arrival timestamp with time zone, origin_location_id character varying(64) NOT NULL, destination_location_id character varying(64) NOT NULL, status character varying(32) NOT NULL, passenger_count integer, cargo_manifest_id character varying(64), PRIMARY KEY (trip_id) )
CREATE TABLE transportation.locations ( location_id character varying(64) NOT NULL, name character varying(255) NOT NULL, type character varying(64) NOT NULL, address_line1 character varying(255), city character varying(128), state_province character varying(128), postal_code character varying(32), country character varying(64) NOT NULL, latitude numeric(9, 6), longitude numeric(9, 6), timezone character varying(64), PRIMARY KEY (location_id) )
CREATE TABLE transportation.maintenance_logs ( log_id character varying(64) NOT NULL, vehicle_id character varying(64) NOT NULL, service_date date NOT NULL, odometer_reading integer, service_type character varying(128) NOT NULL, description text NOT NULL, cost numeric(10, 2), mechanic_name character varying(128), next_service_due_date date, PRIMARY KEY (log_id) )
CREATE TABLE transportation.fuel_logs ( fuel_log_id character varying(64) NOT NULL, vehicle_id character varying(64) NOT NULL, trip_id character varying(64), log_timestamp timestamp with time zone NOT NULL, fuel_type character varying(32) NOT NULL, quantity numeric(10, 3) NOT NULL, unit character varying(16) NOT NULL, cost_per_unit numeric(8, 4), total_cost numeric(10, 2) NOT NULL, odometer_reading integer, location_id character varying(64), PRIMARY KEY (fuel_log_id) )
CREATE TABLE transportation.passengers ( passenger_id character varying(64) NOT NULL, first_name character varying(128) NOT NULL, last_name character varying(128) NOT NULL, email character varying(128) UNIQUE, phone_number character varying(32) UNIQUE, date_of_birth date, loyalty_program_id character varying(64), created_at timestamp with time zone NOT NULL, PRIMARY KEY (passenger_id) )
CREATE TABLE transportation.bookings ( booking_id character varying(64) NOT NULL, passenger_id character varying(64) NOT NULL, trip_id character varying(64) NOT NULL, seat_number character varying(16), booking_time timestamp with time zone NOT NULL, status character varying(32) NOT NULL, fare numeric(10, 2) NOT NULL, payment_transaction_id character varying(128), special_requests text, PRIMARY KEY (booking_id) )

[User] I need a report showing each passenger's total number of bookings and the date of their most recent booking.

[Assistant]
SELECT b.passenger_id,
       COUNT(*) AS total_bookings,
       MAX(b.booking_time) AS last_booking_date
FROM transportation.bookings b
GROUP BY b.passenger_id;

[User] Only include passengers who have made at least 3 bookings.

[Assistant]
SELECT b.passenger_id,
       COUNT(*) AS total_bookings,
       MAX(b.booking_time) AS last_booking_date
FROM transportation.bookings b
GROUP BY b.passenger_id
HAVING COUNT(*) >= 3;

[User] Also include the passenger's full name and email in the result.

[Assistant]
SELECT p.passenger_id,
       p.first_name || ' ' || p.last_name AS full_name,
       p.email,
       COUNT(b.booking_id) AS total_bookings,
       MAX(b.booking_time) AS last_booking_date
FROM transportation.bookings b
JOIN transportation.passengers p ON b.passenger_id = p.passenger_id
GROUP BY p.passenger_id, p.first_name, p.last_name, p.email
HAVING COUNT(b.booking_id) >= 3;

[User] Finally, order the output by total bookings descending and limit to the top 5.

[Assistant]
SELECT p.passenger_id,
       p.first_name || ' ' || p.last_name AS full_name,
       p.email,
       COUNT(b.booking_id) AS total_bookings,
       MAX(b.booking_time) AS last_booking_date
FROM transportation.bookings b
JOIN transportation.passengers p ON b.passenger_id = p.passenger_id
GROUP BY p.passenger_id, p.first_name, p.last_name, p.email
HAVING COUNT(b.booking_id) >= 3
ORDER BY total_bookings DESC
LIMIT 5;

[User] Please provide a list of all trips along with their route details, including the route_number, origin city, and destination city, ordered by scheduled_departure.

[Assistant]
SELECT t.trip_id,
       t.vehicle_id,
       t.driver_id,
       r.route_number,
       ol.city AS origin_city,
       dl.city AS destination_city,
       t.scheduled_departure
FROM transportation.trips t
JOIN transportation.routes r ON t.route_id = r.route_id
JOIN transportation.locations ol ON t.origin_location_id = ol.location_id
JOIN transportation.locations dl ON t.destination_location_id = dl.location_id
ORDER BY t.scheduled_departure;

[User] Give me the vehicle ID, make, model, year, and the total number of trips made by each vehicle.

[Assistant]
SELECT v.vehicle_id, v.make, v.model, v.year, COUNT(t.trip_id) AS total_trips
FROM transportation.vehicles v
LEFT JOIN transportation.trips t ON v.vehicle_id = t.vehicle_id
GROUP BY v.vehicle_id, v.make, v.model, v.year;

[User] List all routes along with the number of unique vehicles assigned to trips on each route.

[Assistant]
SELECT r.route_id, r.route_number, COUNT(DISTINCT t.vehicle_id) AS unique_vehicles
FROM transportation.routes r
LEFT JOIN transportation.trips t ON r.route_id = t.route_id
GROUP BY r.route_id, r.route_number;

[User] Can you add the average passenger count per trip for each route as well?

[Assistant]
SELECT r.route_id, r.route_number, COUNT(DISTINCT t.vehicle_id) AS unique_vehicles, AVG(t.passenger_count) AS avg_passenger_count
FROM transportation.routes r
LEFT JOIN transportation.trips t ON r.route_id = t.route_id
GROUP BY r.route_id, r.route_number;

[User] Only show routes where there have been more than 5 trips.

[Assistant]
SELECT r.route_id, r.route_number, COUNT(DISTINCT t.vehicle_id) AS unique_vehicles, AVG(t.passenger_count) AS avg_passenger_count, COUNT(t.trip_id) AS total_trips
FROM transportation.routes r
LEFT JOIN transportation.trips t ON r.route_id = t.route_id
GROUP BY r.route_id, r.route_number
HAVING COUNT(t.trip_id) > 5;

[User] Please also include the route type and order the results by the average passenger count in descending order.

[Assistant]
SELECT r.route_id, r.route_number, r.type AS route_type, COUNT(DISTINCT t.vehicle_id) AS unique_vehicles, AVG(t.passenger_count) AS avg_passenger_count, COUNT(t.trip_id) AS total_trips
FROM transportation.routes r
LEFT JOIN transportation.trips t ON r.route_id = t.route_id
GROUP BY r.route_id, r.route_number, r.type
HAVING COUNT(t.trip_id) > 5
ORDER BY avg_passenger_count DESC;

[User] Show all trips with the trip ID, route number, and the full description of each route.

[Assistant]
SELECT t.trip_id, r.route_number, r.description
FROM transportation.trips t
JOIN transportation.routes r ON t.route_id = r.route_id;

[User] What is the average maintenance cost per vehicle?

[Assistant]
SELECT vehicle_id, AVG(cost) AS avg_cost
FROM transportation.maintenance_logs
GROUP BY vehicle_id;

[User] Only include vehicles with average maintenance cost greater than 300.

[Assistant]
SELECT vehicle_id, AVG(cost) AS avg_cost
FROM transportation.maintenance_logs
GROUP BY vehicle_id
HAVING AVG(cost) > 300;

[User] Also display the most recent service_date for each vehicle.

[Assistant]
SELECT vehicle_id, AVG(cost) AS avg_cost, MAX(service_date) AS last_service_date
FROM transportation.maintenance_logs
GROUP BY vehicle_id
HAVING AVG(cost) > 300;

[User] Finally, restrict to vehicles that have at least 5 maintenance records.

[Assistant]
SELECT vehicle_id, AVG(cost) AS avg_cost, MAX(service_date) AS last_service_date, COUNT(*) AS service_count
FROM transportation.maintenance_logs
GROUP BY vehicle_id
HAVING AVG(cost) > 300 AND COUNT(*) >= 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 gaming_technology.players (
    player_id uuid NOT NULL DEFAULT gen_random_uuid(), -- unique identifier for the player
    username character varying(100) NOT NULL UNIQUE, -- player's chosen display name
    email character varying(255) NOT NULL UNIQUE, -- player's email address for login/recovery
    password_hash text NOT NULL, -- securely hashed password
    registration_date timestamp with time zone NOT NULL DEFAULT CURRENT_TIMESTAMP, -- when the player account was created
    last_login timestamp with time zone, -- timestamp of the last successful login
    country_code character(2), -- player's country (ISO 3166-1 alpha-2)
    status character varying(20) NOT NULL DEFAULT 'active', -- account status (e.g., active, banned, suspended)
    profile_data jsonb, -- flexible field for avatar url, bio, preferences etc.
    PRIMARY KEY (player_id)
)
CREATE TABLE gaming_technology.games (
    game_id uuid NOT NULL DEFAULT gen_random_uuid(), -- unique identifier for the game
    title character varying(200) NOT NULL, -- official title of the game
    developer_id uuid NOT NULL, -- FK linking to the developers table
    publisher_id uuid, -- FK linking to a potential publishers table (optional)
    genre character varying(100), -- primary genre (e.g., RPG, FPS, Strategy)
    release_date date, -- official release date
    description text, -- short description or synopsis of the game
    platform character varying(50) NOT NULL, -- primary platform (e.g., PC, PlayStation 5, Xbox Series X, Mobile)
    engine character varying(100), -- game engine used (e.g., Unreal Engine 5, Unity)
    website character varying(255), -- official website URL
    PRIMARY KEY (game_id)
    -- FOREIGN KEY (developer_id) REFERENCES gaming_technology.developers(developer_id) -- Example FK constraint
)
CREATE TABLE gaming_technology.game_sessions (
    session_id uuid NOT NULL DEFAULT gen_random_uuid(), -- unique identifier for the game session
    player_id uuid NOT NULL, -- FK linking to the players table
    game_id uuid NOT NULL, -- FK linking to the games table
    server_id uuid, -- FK linking to the servers table (nullable for single-player)
    start_time timestamp with time zone NOT NULL DEFAULT CURRENT_TIMESTAMP, -- when the session began
    end_time timestamp with time zone, -- when the session ended (null if ongoing)
    duration_seconds integer, -- calculated duration of the session in seconds
    score integer, -- player's score for the session, if applicable
    session_data jsonb, -- flexible field for session-specific info (e.g., map played, character used)
    PRIMARY KEY (session_id)
    -- FOREIGN KEY (player_id) REFERENCES gaming_technology.players(player_id),
    -- FOREIGN KEY (game_id) REFERENCES gaming_technology.games(game_id),
    -- FOREIGN KEY (server_id) REFERENCES gaming_technology.servers(server_id)
)
CREATE TABLE gaming_technology.servers (
    server_id uuid NOT NULL DEFAULT gen_random_uuid(), -- unique identifier for the game server instance
    game_id uuid NOT NULL, -- FK linking to the game this server hosts
    server_name character varying(150), -- display name for the server
    region character varying(50) NOT NULL, -- geographical region (e.g., us-east-1, eu-west-2)
    ip_address character varying(45), -- IP address (IPv4 or IPv6)
    port integer, -- network port number
    current_players integer NOT NULL DEFAULT 0, -- number of players currently connected
    max_players integer NOT NULL, -- maximum player capacity
    status character varying(30) NOT NULL DEFAULT 'offline', -- server status (e.g., online, offline, maintenance)
    last_heartbeat timestamp with time zone, -- last time the server reported its status
    PRIMARY KEY (server_id)
    -- FOREIGN KEY (game_id) REFERENCES gaming_technology.games(game_id)
)
CREATE TABLE gaming_technology.achievements (
    achievement_id uuid NOT NULL DEFAULT gen_random_uuid(), -- unique identifier for an achievement definition
    game_id uuid NOT NULL, -- FK linking to the game the achievement belongs to
    name character varying(150) NOT NULL, -- name of the achievement
    description text NOT NULL, -- how to unlock the achievement
    icon_url character varying(255), -- URL for the achievement's icon
    points integer DEFAULT 0, -- points awarded for unlocking (optional)
    hidden boolean DEFAULT false, -- whether the achievement details are hidden until unlocked
    PRIMARY KEY (achievement_id)
    -- FOREIGN KEY (game_id) REFERENCES gaming_technology.games(game_id)
)
CREATE TABLE gaming_technology.player_achievements (
    player_achievement_id uuid NOT NULL DEFAULT gen_random_uuid(), -- unique identifier for this unlock instance
    player_id uuid NOT NULL, -- FK linking to the player who unlocked it
    achievement_id uuid NOT NULL, -- FK linking to the achievement definition
    unlocked_at timestamp with time zone NOT NULL DEFAULT CURRENT_TIMESTAMP, -- when the achievement was unlocked
    PRIMARY KEY (player_achievement_id),
    UNIQUE (player_id, achievement_id) -- Ensure a player can only unlock an achievement once
    -- FOREIGN KEY (player_id) REFERENCES gaming_technology.players(player_id),
    -- FOREIGN KEY (achievement_id) REFERENCES gaming_technology.achievements(achievement_id)
)
CREATE TABLE gaming_technology.in_game_items (
    item_id uuid NOT NULL DEFAULT gen_random_uuid(), -- unique identifier for the item definition
    game_id uuid NOT NULL, -- FK linking to the game this item belongs to
    item_name character varying(150) NOT NULL, -- name of the item
    item_type character varying(50) NOT NULL, -- type (e.g., Cosmetic, Consumable, Weapon, Armor)
    description text, -- description of the item
    rarity character varying(30), -- item rarity (e.g., Common, Rare, Epic, Legendary)
    cost_currency character varying(10), -- currency code if purchasable (e.g., USD, EUR, GOLD)
    cost_amount numeric(12, 2), -- price if purchasable
    attributes jsonb, -- flexible field for item stats or properties
    PRIMARY KEY (item_id)
    -- FOREIGN KEY (game_id) REFERENCES gaming_technology.games(game_id)
)
CREATE TABLE gaming_technology.player_inventory (
    inventory_id uuid NOT NULL DEFAULT gen_random_uuid(), -- unique identifier for an inventory entry
    player_id uuid NOT NULL, -- FK linking to the player owning the item
    item_id uuid NOT NULL, -- FK linking to the item definition
    quantity integer NOT NULL DEFAULT 1, -- number of items held (for stackable items)
    acquired_at timestamp with time zone NOT NULL DEFAULT CURRENT_TIMESTAMP, -- when the item was acquired
    instance_data jsonb, -- data specific to this instance (e.g., weapon mods, durability)
    PRIMARY KEY (inventory_id),
    -- Optional unique constraint if items are non-stackable or unique instances
    -- UNIQUE (player_id, item_id) -- Use if quantity is always 1
    -- FOREIGN KEY (player_id) REFERENCES gaming_technology.players(player_id),
    -- FOREIGN KEY (item_id) REFERENCES gaming_technology.in_game_items(item_id)
)

[User] Show usernames of players who own items of 'Legendary' rarity.

[Assistant] SELECT DISTINCT T1.username FROM players AS T1 JOIN player_inventory AS T2 ON T1.player_id = T2.player_id JOIN in_game_items AS T3 ON T2.item_id = T3.item_id WHERE T3.rarity = 'Legendary';

[User] Modify the query to also include the item name and the quantity the player owns for each such item.

[Assistant] SELECT T1.username, T3.item_name, T2.quantity FROM players AS T1 JOIN player_inventory AS T2 ON T1.player_id = T2.player_id JOIN in_game_items AS T3 ON T2.item_id = T3.item_id WHERE T3.rarity = 'Legendary';

[User] Change the request to find the total number of 'Legendary' items across all player inventories.

[Assistant] SELECT SUM(T1.quantity) FROM player_inventory AS T1 JOIN in_game_items AS T2 ON T1.item_id = T2.item_id WHERE T2.rarity = 'Legendary';

[User] Show the total number of 'Legendary' items per game, including the game title.

[Assistant] SELECT T3.title, SUM(T1.quantity) FROM player_inventory AS T1 JOIN in_game_items AS T2 ON T1.item_id = T2.item_id JOIN games AS T3 ON T2.game_id = T3.game_id WHERE T2.rarity = 'Legendary' GROUP BY T3.title;

[User] List game titles released on the 'PC' platform along with the count of servers currently hosting each game.

[Assistant] SELECT T1.title, count(T2.server_id) FROM games AS T1 JOIN servers AS T2 ON T1.game_id = T2.game_id WHERE T1.platform = 'PC' GROUP BY T1.title;

[User] Now, only show games with more than 3 servers and sort the results by the server count in descending order.

[Assistant] SELECT T1.title, count(T2.server_id) AS server_count FROM games AS T1 JOIN servers AS T2 ON T1.game_id = T2.game_id WHERE T1.platform = 'PC' GROUP BY T1.title HAVING count(T2.server_id) > 3 ORDER BY server_count DESC;

[User] How many players are there in each country?

[Assistant]
SELECT country_code, COUNT(*) AS player_count
FROM gaming_technology.players
GROUP BY country_code;

[User] Only include countries with more than 10 players.

[Assistant]
SELECT country_code, COUNT(*) AS player_count
FROM gaming_technology.players
GROUP BY country_code
HAVING COUNT(*) > 10;

[User] Also calculate what percentage of the total players each country represents.

[Assistant]
SELECT country_code,
       player_count,
       ROUND(player_count * 100.0 / total.total_players, 2) AS percentage_of_all
FROM (
  SELECT country_code, COUNT(*) AS player_count
  FROM gaming_technology.players
  GROUP BY country_code
  HAVING COUNT(*) > 10
) AS country_data
CROSS JOIN (
  SELECT COUNT(*) AS total_players
  FROM gaming_technology.players
) AS total;

[User] Order the results by this percentage in ascending order.

[Assistant]
SELECT country_code,
       player_count,
       ROUND(player_count * 100.0 / total.total_players, 2) AS percentage_of_all
FROM (
  SELECT country_code, COUNT(*) AS player_count
  FROM gaming_technology.players
  GROUP BY country_code
  HAVING COUNT(*) > 10
) AS country_data
CROSS JOIN (
  SELECT COUNT(*) AS total_players
  FROM gaming_technology.players
) AS total
ORDER BY percentage_of_all ASC;

[User] Show me the count of game servers available for each game platform. Include the platform name and the server count.

[Assistant] SELECT g.platform, COUNT(s.server_id) AS server_count FROM gaming_technology.servers AS s JOIN gaming_technology.games AS g ON s.game_id = g.game_id WHERE g.platform IS NOT NULL GROUP BY g.platform ORDER BY g.platform;

[User] Okay, now only include servers that are currently 'online'.

[Assistant] SELECT g.platform, COUNT(s.server_id) AS server_count FROM gaming_technology.servers AS s JOIN gaming_technology.games AS g ON s.game_id = g.game_id WHERE g.platform IS NOT NULL AND s.status = 'online' GROUP BY g.platform ORDER BY g.platform;

[User] Instead of ordering by platform, can you order the results by the server count in descending order?

[Assistant] SELECT g.platform, COUNT(s.server_id) AS server_count FROM gaming_technology.servers AS s JOIN gaming_technology.games AS g ON s.game_id = g.game_id WHERE g.platform IS NOT NULL AND s.status = 'online' GROUP BY g.platform ORDER BY server_count DESC;

[User] Show the usernames and registration dates for all players whose status is 'inactive'.

[Assistant] SELECT username, registration_date FROM players WHERE status = 'inactive';

[User] Refine the list to only include players registered after '2023-01-01'.

[Assistant] SELECT username, registration_date FROM players WHERE status = 'inactive' AND registration_date >= '2023-01-01';

[User] Instead, find the number of unique players who registered before '2020-01-01' and have never logged in (last_login is NULL).

[Assistant] SELECT count(player_id) FROM players WHERE registration_date < '2020-01-01' AND last_login IS NULL;

[User] List the usernames and registration dates for those specific players instead of just the count.

[Assistant] SELECT username, registration_date FROM players WHERE registration_date < '2020-01-01' AND last_login IS NULL;

[User] Show me each player's last_login and the end_time of their most recent game session.

[Assistant]
SELECT p.player_id,
       p.username,
       p.last_login,
       gs.last_end_time
FROM gaming_technology.players p
LEFT JOIN (
  SELECT player_id, MAX(end_time) AS last_end_time
  FROM gaming_technology.game_sessions
  GROUP BY player_id
) gs ON p.player_id = gs.player_id;

[User] Only list players whose status is 'active'.

[Assistant]
SELECT p.player_id,
       p.username,
       p.last_login,
       gs.last_end_time
FROM gaming_technology.players p
LEFT JOIN (
  SELECT player_id, MAX(end_time) AS last_end_time
  FROM gaming_technology.game_sessions
  GROUP BY player_id
) gs ON p.player_id = gs.player_id
WHERE p.status = 'active';

[User] Also include the title of the game from that most recent session.

[Assistant]
WITH latest AS (
  SELECT DISTINCT ON (player_id) player_id, end_time, game_id
  FROM gaming_technology.game_sessions
  WHERE end_time IS NOT NULL
  ORDER BY player_id, end_time DESC
)
SELECT p.player_id,
       p.username,
       p.last_login,
       l.end_time AS last_end_time,
       g.title AS last_game_title
FROM gaming_technology.players p
LEFT JOIN latest l ON p.player_id = l.player_id
LEFT JOIN gaming_technology.games g ON l.game_id = g.game_id
WHERE p.status = 'active';


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

[User] I need to find users who have liked both a post and a comment on the same day. For each such user and date, list user_id, date, post_id, and comment_id.

[Assistant]
SELECT p.user_id, DATE(p.created_at) AS like_date, p.post_id, c.comment_id
FROM social_media.likes p
JOIN social_media.likes c
  ON p.user_id = c.user_id
  AND DATE(p.created_at) = DATE(c.created_at)
WHERE p.post_id IS NOT NULL
  AND c.comment_id IS NOT NULL;

[User] Actually, I only want cases where the post and comment were liked within two hours of each other.

[Assistant]
SELECT p.user_id, DATE(p.created_at) AS like_date, p.post_id, c.comment_id
FROM social_media.likes p
JOIN social_media.likes c
  ON p.user_id = c.user_id
  AND DATE(p.created_at) = DATE(c.created_at)
WHERE p.post_id IS NOT NULL
  AND c.comment_id IS NOT NULL
  AND ABS(EXTRACT(EPOCH FROM (p.created_at - c.created_at))) <= 7200;

[User] Please order the results by like_date descending.

[Assistant]
SELECT p.user_id, DATE(p.created_at) AS like_date, p.post_id, c.comment_id
FROM social_media.likes p
JOIN social_media.likes c
  ON p.user_id = c.user_id
  AND DATE(p.created_at) = DATE(c.created_at)
WHERE p.post_id IS NOT NULL
  AND c.comment_id IS NOT NULL
  AND ABS(EXTRACT(EPOCH FROM (p.created_at - c.created_at))) <= 7200
ORDER BY like_date DESC;

[User] Also, limit the output to the top 10 records.

[Assistant]
SELECT p.user_id, DATE(p.created_at) AS like_date, p.post_id, c.comment_id
FROM social_media.likes p
JOIN social_media.likes c
  ON p.user_id = c.user_id
  AND DATE(p.created_at) = DATE(c.created_at)
WHERE p.post_id IS NOT NULL
  AND c.comment_id IS NOT NULL
  AND ABS(EXTRACT(EPOCH FROM (p.created_at - c.created_at))) <= 7200
ORDER BY like_date DESC
LIMIT 10;

[User] Show the total number of likes made by each user, including the user_id and their like count.

[Assistant] SELECT user_id, COUNT(*) AS like_count FROM social_media.likes GROUP BY user_id;

[User] Only show users who have made more than 50 likes.

[Assistant] SELECT user_id, COUNT(*) AS like_count FROM social_media.likes GROUP BY user_id HAVING COUNT(*) > 50;

[User] Retrieve pairs of likes where the same user liked two different posts. For each pair, show user_id, p1.post_id AS first_post_id, p2.post_id AS second_post_id, and the time difference in minutes between the two likes.

[Assistant]
SELECT p1.user_id,
       p1.post_id AS first_post_id,
       p2.post_id AS second_post_id,
       ABS(EXTRACT(EPOCH FROM (p1.created_at - p2.created_at)))/60 AS minutes_diff
FROM social_media.likes p1
JOIN social_media.likes p2
  ON p1.user_id = p2.user_id
  AND p1.post_id <> p2.post_id;

[User] Only include pairs where the time difference is less than 30 minutes.

[Assistant]
SELECT p1.user_id,
       p1.post_id AS first_post_id,
       p2.post_id AS second_post_id,
       ABS(EXTRACT(EPOCH FROM (p1.created_at - p2.created_at)))/60 AS minutes_diff
FROM social_media.likes p1
JOIN social_media.likes p2
  ON p1.user_id = p2.user_id
  AND p1.post_id <> p2.post_id
WHERE ABS(EXTRACT(EPOCH FROM (p1.created_at - p2.created_at)))/60 < 30;

[User] What is the total number of likes recorded in the system?

[Assistant] SELECT COUNT(*) FROM social_media.likes;

[User] Count the total number of likes each post has received.

[Assistant]
SELECT post_id, COUNT(*) AS like_count
FROM social_media.likes
WHERE post_id IS NOT NULL
GROUP BY post_id;

[User] List all likes made by user 'U100' on posts, including the like_id and the post_id.

[Assistant] SELECT like_id, post_id FROM social_media.likes WHERE user_id = 'U100' AND post_id IS NOT NULL;

[User] Now, only include those likes created after '2024-01-01'.

[Assistant] SELECT like_id, post_id FROM social_media.likes WHERE user_id = 'U100' AND post_id IS NOT NULL AND created_at > '2024-01-01';

[User] Instead of listing them, count how many such likes user 'U100' made after '2024-01-01'.

[Assistant] SELECT COUNT(*) FROM social_media.likes WHERE user_id = 'U100' AND post_id IS NOT NULL AND created_at > '2024-01-01';

[User] How many likes did user 'U100' make on comments after '2024-01-01'?

[Assistant] SELECT COUNT(*) FROM social_media.likes WHERE user_id = 'U100' AND comment_id IS NOT NULL AND created_at > '2024-01-01';


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE web3.tokens ( token_id text PRIMARY KEY, contract_address text, token_name text, token_symbol text, decimals int, total_supply numeric )

[User] Find all pairs of tokens that have the same contract_address but different token_symbols. Show both token_ids, each token's symbol, and the shared contract_address.

[Assistant] SELECT t1.token_id AS token_id_1, t2.token_id AS token_id_2, t1.token_symbol AS symbol_1, t2.token_symbol AS symbol_2, t1.contract_address FROM web3.tokens t1 JOIN web3.tokens t2 ON t1.contract_address = t2.contract_address AND t1.token_id < t2.token_id AND t1.token_symbol <> t2.token_symbol;

[User] List all tokens along with the contract addresses for symbols that appear more than once.

[Assistant]
SELECT t.token_id, t.token_symbol, t.contract_address
FROM web3.tokens t
JOIN (
  SELECT token_symbol
  FROM web3.tokens
  GROUP BY token_symbol
  HAVING COUNT(*) > 1
) dup ON t.token_symbol = dup.token_symbol;

[User] What is the average total_supply for each decimals value?

[Assistant]
SELECT decimals, AVG(total_supply) AS avg_supply
FROM web3.tokens
GROUP BY decimals;

[User] Actually, I only want to include tokens whose token_symbol starts with 'A'.

[Assistant]
SELECT decimals, AVG(total_supply) AS avg_supply
FROM web3.tokens
WHERE token_symbol LIKE 'A%'
GROUP BY decimals;

[User] Show all tokens where the total_supply is less than 10000, listing the token_id, token_symbol, and decimals.

[Assistant] SELECT token_id, token_symbol, decimals FROM web3.tokens WHERE total_supply < 10000;

[User] Actually, please also include the token_name in the result and order the results by total_supply ascending.

[Assistant] SELECT token_id, token_symbol, token_name, decimals FROM web3.tokens WHERE total_supply < 10000 ORDER BY total_supply ASC;

[User] Show me the token names and their contract addresses where the total supply is greater than 1 million, sorted by total supply in descending order.

[Assistant] SELECT token_name, contract_address FROM web3.tokens WHERE total_supply > 1000000 ORDER BY total_supply DESC;

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

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


System:
You are an 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 character varying(64) NOT NULL, user_id character varying(64) NOT NULL, address character varying(128) NOT NULL, private_key text NOT NULL, created_at timestamp NOT NULL, PRIMARY KEY (wallet_id) )
CREATE TABLE trading_platform.orders ( order_id text PRIMARY KEY, user_id text, wallet_id text, asset_id text, order_type text, quantity numeric, price numeric, status text, created_at timestamp )
CREATE TABLE trading_platform.utxos ( utxo_id.text, transaction_id.text, output_index.integer, address.text, amount.numeric, spent.boolean )
CREATE TABLE trading_platform.dapps ( dapp_id.text, name.text, description.text, url.text )
CREATE TABLE trading_platform.peers ( peer_id.text, ip_address.text, port.integer, last_seen.timestamp )
CREATE TABLE trading_platform.metadata (
    metadata_id character varying(64) NOT NULL,  -- unique identifier for the metadata
    asset_id character varying(64) NOT NULL, -- identifier of the asset the metadata is associated with
    key character varying(128) NOT NULL, -- key of the metadata
    value text NOT NULL, -- value of the metadata
    PRIMARY KEY (metadata_id)
)
CREATE TABLE trading_platform.kyc_audit (
    kyc_audit_id character varying(64) NOT NULL,  -- unique identifier for the KYC audit
    user_id character varying(64) NOT NULL, -- identifier of the user being audited
    status character varying(32) NOT NULL, -- status of the KYC audit (e.g., pending, approved, rejected)
    reviewed_at timestamp NOT NULL, -- time when the KYC audit was reviewed
    PRIMARY KEY (kyc_audit_id)
)

[User] Count the number of metadata entries for each asset.

[Assistant]
SELECT asset_id, COUNT(*) AS metadata_count
FROM trading_platform.metadata
GROUP BY asset_id;

[User] List all peers with their IP addresses who have not been seen in the last 7 days.

[Assistant]
SELECT peer_id, ip_address, port, last_seen
FROM trading_platform.peers
WHERE last_seen < NOW() - INTERVAL '7 days';

[User] Show me, for each wallet address, the total sum of amounts for all unspent UTXOs, along with the user ID who owns the wallet.

[Assistant]
SELECT w.address, w.user_id, COALESCE(SUM(u.amount), 0) AS total_unspent_amount
FROM trading_platform.wallets w
LEFT JOIN trading_platform.utxos u
  ON w.address = u.address AND (u.spent = FALSE OR u.spent IS NULL)
GROUP BY w.address, w.user_id;

[User] Now, include only the wallets where the total unspent amount is greater than 50, and show the wallet_id as well.

[Assistant]
SELECT w.wallet_id, w.address, w.user_id, COALESCE(SUM(u.amount), 0) AS total_unspent_amount
FROM trading_platform.wallets w
LEFT JOIN trading_platform.utxos u
  ON w.address = u.address AND (u.spent = FALSE OR u.spent IS NULL)
GROUP BY w.wallet_id, w.address, w.user_id
HAVING COALESCE(SUM(u.amount), 0) > 50;

[User] Show me each user's username, their wallet address, and the total quantity of open orders they have placed, along with the name of the asset for each order.

[Assistant]
SELECT u.username, w.address, o.asset_id, SUM(o.quantity) AS total_open_quantity
FROM trading_platform.users u
JOIN trading_platform.wallets w ON u.user_id = w.user_id
JOIN trading_platform.orders o ON w.wallet_id = o.wallet_id
WHERE o.status = 'open'
GROUP BY u.username, w.address, o.asset_id
ORDER BY u.username, w.address, o.asset_id;

[User] Can you also include the email address for each user and only show those with at least 2 open orders?

[Assistant]
SELECT u.username, u.email, w.address, o.asset_id, SUM(o.quantity) AS total_open_quantity, COUNT(o.order_id) AS open_order_count
FROM trading_platform.users u
JOIN trading_platform.wallets w ON u.user_id = w.user_id
JOIN trading_platform.orders o ON w.wallet_id = o.wallet_id
WHERE o.status = 'open'
GROUP BY u.username, u.email, w.address, o.asset_id
HAVING COUNT(o.order_id) >= 2
ORDER BY u.username, w.address, o.asset_id;

[User] For each asset, show the asset_id, the number of associated metadata entries, and the quantity of orders placed for that asset.

[Assistant]
SELECT a.asset_id,
       COUNT(DISTINCT m.metadata_id) AS metadata_count,
       COUNT(o.order_id) AS order_count
FROM (SELECT DISTINCT asset_id FROM trading_platform.metadata
      UNION
      SELECT DISTINCT asset_id FROM trading_platform.orders) a
LEFT JOIN trading_platform.metadata m ON a.asset_id = m.asset_id
LEFT JOIN trading_platform.orders o ON a.asset_id = o.asset_id
GROUP BY a.asset_id
ORDER BY a.asset_id;

[User] The query failed because some assets do not have metadata. Please ensure all assets from the orders table are included, with metadata_count as 0 when none exist.

[Assistant]
SELECT a.asset_id,
       COALESCE(COUNT(m.metadata_id), 0) AS metadata_count,
       COUNT(o.order_id) AS order_count
FROM (
    SELECT DISTINCT asset_id FROM trading_platform.orders
) a
LEFT JOIN trading_platform.metadata m ON a.asset_id = m.asset_id
LEFT JOIN trading_platform.orders o ON a.asset_id = o.asset_id
GROUP BY a.asset_id
ORDER BY a.asset_id;

[User] Thanks. Now, could you also show the total number of unique users who have placed orders for each asset?

[Assistant]
SELECT a.asset_id,
       COALESCE(COUNT(m.metadata_id), 0) AS metadata_count,
       COUNT(o.order_id) AS order_count,
       COUNT(DISTINCT o.user_id) AS unique_user_count
FROM (
    SELECT DISTINCT asset_id FROM trading_platform.orders
) a
LEFT JOIN trading_platform.metadata m ON a.asset_id = m.asset_id
LEFT JOIN trading_platform.orders o ON a.asset_id = o.asset_id
GROUP BY a.asset_id
ORDER BY a.asset_id;

[User] Only include assets with at least 3 different users placing orders, and show the results ordered by unique_user_count descending.

[Assistant]
SELECT a.asset_id,
       COALESCE(COUNT(m.metadata_id), 0) AS metadata_count,
       COUNT(o.order_id) AS order_count,
       COUNT(DISTINCT o.user_id) AS unique_user_count
FROM (
    SELECT DISTINCT asset_id FROM trading_platform.orders
) a
LEFT JOIN trading_platform.metadata m ON a.asset_id = m.asset_id
LEFT JOIN trading_platform.orders o ON a.asset_id = o.asset_id
GROUP BY a.asset_id
HAVING COUNT(DISTINCT o.user_id) >= 3
ORDER BY unique_user_count DESC;

[User] I want each user with the date and action of their most recent log entry, along with how many log entries they have in the last 7 days.

[Assistant]
WITH recent_logs AS (
  SELECT user_id, action, logged_at,
         ROW_NUMBER() OVER (PARTITION BY user_id ORDER BY logged_at DESC) AS rn
  FROM trading_platform.logs
  WHERE logged_at >= NOW() - INTERVAL '7 days'
)
SELECT u.user_id,
       u.username,
       rl.logged_at   AS latest_log_date,
       rl.action      AS latest_action,
       COUNT(l.*)     AS log_count
FROM trading_platform.users u
LEFT JOIN recent_logs rl
  ON u.user_id = rl.user_id AND rl.rn = 1
LEFT JOIN trading_platform.logs l
  ON u.user_id = l.user_id
  AND l.logged_at >= NOW() - INTERVAL '7 days'
GROUP BY u.user_id, u.username, rl.logged_at, rl.action;

[User] Actually, I only care about log actions that contain the word 'trade'.

[Assistant]
WITH recent_logs AS (
  SELECT user_id, action, logged_at,
         ROW_NUMBER() OVER (PARTITION BY user_id ORDER BY logged_at DESC) AS rn
  FROM trading_platform.logs
  WHERE logged_at >= NOW() - INTERVAL '7 days'
    AND action ILIKE '%trade%'
)
SELECT u.user_id,
       u.username,
       rl.logged_at   AS latest_log_date,
       rl.action      AS latest_action,
       COUNT(l.*)     AS log_count
FROM trading_platform.users u
LEFT JOIN recent_logs rl
  ON u.user_id = rl.user_id AND rl.rn = 1
LEFT JOIN trading_platform.logs l
  ON u.user_id = l.user_id
  AND l.logged_at >= NOW() - INTERVAL '7 days'
  AND l.action ILIKE '%trade%'
GROUP BY u.user_id, u.username, rl.logged_at, rl.action;

[User] Include users who have no such logs, showing null for latest_action and latest_log_date, and zero for log_count.

[Assistant]
WITH recent_logs AS (
  SELECT user_id, action, logged_at,
         ROW_NUMBER() OVER (PARTITION BY user_id ORDER BY logged_at DESC) AS rn
  FROM trading_platform.logs
  WHERE logged_at >= NOW() - INTERVAL '7 days'
    AND action ILIKE '%trade%'
)
SELECT u.user_id,
       u.username,
       rl.logged_at   AS latest_log_date,
       rl.action      AS latest_action,
       COALESCE(cnt.log_count, 0) AS log_count
FROM trading_platform.users u
LEFT JOIN a recent AS (
  SELECT user_id, COUNT(*) AS log_count
  FROM trading_platform.logs
  WHERE logged_at >= NOW() - INTERVAL '7 days'
    AND action ILIKE '%trade%'
  GROUP BY user_id
) cnt ON u.user_id = cnt.user_id
LEFT JOIN recent_logs rl
  ON u.user_id = rl.user_id AND rl.rn = 1;

[User] Finally, order the results by log_count ascending.

[Assistant]
WITH recent_logs AS (
  SELECT user_id, action, logged_at,
         ROW_NUMBER() OVER (PARTITION BY user_id ORDER BY logged_at DESC) AS rn
  FROM trading_platform.logs
  WHERE logged_at >= NOW() - INTERVAL '7 days'
    AND action ILIKE '%trade%'
),
log_counts AS (
  SELECT user_id, COUNT(*) AS log_count
  FROM trading_platform.logs
  WHERE logged_at >= NOW() - INTERVAL '7 days'
    AND action ILIKE '%trade%'
  GROUP BY user_id
)
SELECT u.user_id,
       u.username,
       rl.logged_at    AS latest_log_date,
       rl.action       AS latest_action,
       COALESCE(lc.log_count, 0) AS log_count
FROM trading_platform.users u
LEFT JOIN log_counts lc
  ON u.user_id = lc.user_id
LEFT JOIN recent_logs rl
  ON u.user_id = rl.user_id AND rl.rn = 1
ORDER BY log_count ASC;


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

[User] For each location, what is the average appointment duration? Show location_id and the average duration.

[Assistant] SELECT location_id, AVG(duration_minutes) FROM healthcare.appointments GROUP BY location_id;

[User] Show all appointments that have 'follow-up' mentioned in the notes field.

[Assistant] SELECT * FROM healthcare.appointments WHERE notes LIKE '%follow-up%';

[User] For each patient, find the next appointment after each one. Return patient_id, appointment_id AS current_appointment, next_appointment_id, and waiting_time in minutes.

[Assistant]
SELECT a.patient_id,
       a.appointment_id AS current_appointment,
       b.appointment_id AS next_appointment_id,
       EXTRACT(EPOCH FROM (b.appointment_time - a.appointment_time)) / 60 AS waiting_time
FROM healthcare.appointments a
JOIN healthcare.appointments b
  ON a.patient_id = b.patient_id
 AND b.appointment_time = (
     SELECT MIN(appointment_time)
     FROM healthcare.appointments
     WHERE patient_id = a.patient_id
       AND appointment_time > a.appointment_time
 ) ;

[User] Only include waiting times less than 30 minutes.

[Assistant]
SELECT a.patient_id,
       a.appointment_id AS current_appointment,
       b.appointment_id AS next_appointment_id,
       EXTRACT(EPOCH FROM (b.appointment_time - a.appointment_time)) / 60 AS waiting_time
FROM healthcare.appointments a
JOIN healthcare.appointments b
  ON a.patient_id = b.patient_id
 AND b.appointment_time = (
     SELECT MIN(appointment_time)
     FROM healthcare.appointments
     WHERE patient_id = a.patient_id
       AND appointment_time > a.appointment_time
 )
WHERE EXTRACT(EPOCH FROM (b.appointment_time - a.appointment_time)) / 60 < 30;

[User] Get the total number of appointments grouped by status.

[Assistant]
SELECT status,
       COUNT(*) AS appointment_count
FROM healthcare.appointments
GROUP BY status;

[User] Now filter to include only statuses with more than 50 appointments.

[Assistant]
SELECT status,
       COUNT(*) AS appointment_count
FROM healthcare.appointments
GROUP BY status
HAVING COUNT(*) > 50;

[User] Find overlapping appointments for each doctor. Return doctor_id, appointment_id_1, appointment_id_2, and overlap duration in minutes.

[Assistant]
SELECT a.doctor_id,
       a.appointment_id AS appointment_id_1,
       b.appointment_id AS appointment_id_2,
       EXTRACT(EPOCH FROM (LEAST(a.appointment_time + (INTERVAL '1 minute' * a.duration_minutes),
                               b.appointment_time + (INTERVAL '1 minute' * b.duration_minutes))
                         - GREATEST(a.appointment_time, b.appointment_time))) / 60 AS overlap_minutes
FROM healthcare.appointments a
JOIN healthcare.appointments b
  ON a.doctor_id = b.doctor_id
 AND a.appointment_id < b.appointment_id
WHERE a.appointment_time < b.appointment_time + (INTERVAL '1 minute' * b.duration_minutes)
  AND b.appointment_time < a.appointment_time + (INTERVAL '1 minute' * a.duration_minutes);

[User] Exclude overlaps less than 15 minutes.

[Assistant]
SELECT a.doctor_id,
       a.appointment_id AS appointment_id_1,
       b.appointment_id AS appointment_id_2,
       EXTRACT(EPOCH FROM (LEAST(a.appointment_time + (INTERVAL '1 minute' * a.duration_minutes),
                               b.appointment_time + (INTERVAL '1 minute' * b.duration_minutes))
                         - GREATEST(a.appointment_time, b.appointment_time))) / 60 AS overlap_minutes
FROM healthcare.appointments a
JOIN healthcare.appointments b
  ON a.doctor_id = b.doctor_id
 AND a.appointment_id < b.appointment_id
WHERE a.appointment_time < b.appointment_time + (INTERVAL '1 minute' * b.duration_minutes)
  AND b.appointment_time < a.appointment_time + (INTERVAL '1 minute' * a.duration_minutes)
HAVING (EXTRACT(EPOCH FROM (LEAST(a.appointment_time + (INTERVAL '1 minute' * a.duration_minutes),
                               b.appointment_time + (INTERVAL '1 minute' * b.duration_minutes))
                         - GREATEST(a.appointment_time, b.appointment_time))) / 60) >= 15;

[User] Also only include overlaps where status is 'Scheduled' for both appointments.

[Assistant]
SELECT a.doctor_id,
       a.appointment_id AS appointment_id_1,
       b.appointment_id AS appointment_id_2,
       EXTRACT(EPOCH FROM (LEAST(a.appointment_time + (INTERVAL '1 minute' * a.duration_minutes),
                               b.appointment_time + (INTERVAL '1 minute' * b.duration_minutes))
                         - GREATEST(a.appointment_time, b.appointment_time))) / 60 AS overlap_minutes
FROM healthcare.appointments a
JOIN healthcare.appointments b
  ON a.doctor_id = b.doctor_id
 AND a.appointment_id < b.appointment_id
WHERE a.status = 'Scheduled'
  AND b.status = 'Scheduled'
  AND a.appointment_time < b.appointment_time + (INTERVAL '1 minute' * b.duration_minutes)
  AND b.appointment_time < a.appointment_time + (INTERVAL '1 minute' * a.duration_minutes)
HAVING (EXTRACT(EPOCH FROM (LEAST(a.appointment_time + (INTERVAL '1 minute' * a.duration_minutes),
                               b.appointment_time + (INTERVAL '1 minute' * b.duration_minutes))
                         - GREATEST(a.appointment_time, b.appointment_time))) / 60) >= 15;

[User] For each patient, find the next appointment after each one. Return patient_id, appointment_id, next_appointment_id, and the waiting time in minutes between them.

[Assistant]
SELECT A.patient_id,
       A.appointment_id AS current_id,
       B.appointment_id AS next_id,
       EXTRACT(EPOCH FROM (B.appointment_time - A.appointment_time)) / 60 AS wait_minutes
FROM healthcare.appointments A
JOIN healthcare.appointments B
  ON A.patient_id = B.patient_id
 AND B.appointment_time = (
       SELECT MIN(appointment_time)
       FROM healthcare.appointments
       WHERE patient_id = A.patient_id
         AND appointment_time > A.appointment_time
   );

[User] Now include only the pairs where the waiting time is less than 30 minutes.

[Assistant]
SELECT A.patient_id,
       A.appointment_id AS current_id,
       B.appointment_id AS next_id,
       EXTRACT(EPOCH FROM (B.appointment_time - A.appointment_time)) / 60 AS wait_minutes
FROM healthcare.appointments A
JOIN healthcare.appointments B
  ON A.patient_id = B.patient_id
 AND B.appointment_time = (
       SELECT MIN(appointment_time)
       FROM healthcare.appointments
       WHERE patient_id = A.patient_id
         AND appointment_time > A.appointment_time
   )
WHERE EXTRACT(EPOCH FROM (B.appointment_time - A.appointment_time)) / 60 < 30;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE legal_services.clients ( client_id character varying(64) NOT NULL, first_name character varying(100) NOT NULL, last_name character varying(100) NOT NULL, company_name character varying(200), email character varying(128) UNIQUE NOT NULL, phone character varying(32), address text, date_registered timestamp NOT NULL, status character varying(32) NOT NULL, PRIMARY KEY (client_id) )
CREATE TABLE legal_services.law_firms ( firm_id character varying(64) NOT NULL, firm_name character varying(200) NOT NULL, address text NOT NULL, phone character varying(32), website character varying(255), founded_date date, managing_partner_id character varying(64), PRIMARY KEY (firm_id) )
CREATE TABLE legal_services.cases ( case_id character varying(64) NOT NULL, case_number character varying(100) UNIQUE, case_name text NOT NULL, client_id character varying(64) NOT NULL, lead_lawyer_id character varying(64) NOT NULL, case_type character varying(100) NOT NULL, status character varying(50) NOT NULL, date_opened timestamp NOT NULL, date_closed timestamp, description text, court_jurisdiction character varying(128), PRIMARY KEY (case_id) )
CREATE TABLE legal_services.documents ( document_id character varying(64) NOT NULL, case_id character varying(64) NOT NULL, document_name character varying(255) NOT NULL, document_type character varying(100), storage_path text NOT NULL, uploaded_by_lawyer_id character varying(64), upload_timestamp timestamp NOT NULL, version integer DEFAULT 1, description text, PRIMARY KEY (document_id) )
CREATE TABLE legal_services.appointments ( appointment_id character varying(64) NOT NULL, client_id character varying(64) NOT NULL, lawyer_id character varying(64) NOT NULL, case_id character varying(64), start_time timestamp NOT NULL, end_time timestamp NOT NULL, location text, subject character varying(255), notes text, status character varying(50) NOT NULL, created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, PRIMARY KEY (appointment_id) )

[User] Show me all cases opened in the year 2024, along with the full name of the client for each case.

[Assistant] SELECT T1.case_number, T1.case_name, T2.first_name, T2.last_name FROM cases AS T1 JOIN clients AS T2 ON T1.client_id = T2.client_id WHERE T1.date_opened >= '2024-01-01' AND T1.date_opened < '2025-01-01';

[User] Can you refine this to only include cases of type 'Corporate Law'?

[Assistant] SELECT T1.case_number, T1.case_name, T2.first_name, T2.last_name FROM cases AS T1 JOIN clients AS T2 ON T1.client_id = T2.client_id WHERE T1.date_opened >= '2024-01-01' AND T1.date_opened < '2025-01-01' AND T1.case_type = 'Corporate Law';

[User] Also, for each of these cases, include the total number of documents uploaded.

[Assistant] SELECT T1.case_number, T1.case_name, T2.first_name, T2.last_name, COUNT(T3.document_id) AS document_count FROM cases AS T1 JOIN clients AS T2 ON T1.client_id = T2.client_id LEFT JOIN documents AS T3 ON T1.case_id = T3.case_id WHERE T1.date_opened >= '2024-01-01' AND T1.date_opened < '2025-01-01' AND T1.case_type = 'Corporate Law' GROUP BY T1.case_id, T1.case_number, T1.case_name, T2.client_id, T2.first_name, T2.last_name ORDER BY T1.date_opened;

[User] List all law firms, showing their name, website, and the ID of their managing partner.

[Assistant] SELECT firm_name, website, managing_partner_id FROM law_firms;

[User] Only include firms where the managing partner ID starts with 'MPG_'.

[Assistant] SELECT firm_name, website, managing_partner_id FROM law_firms WHERE managing_partner_id LIKE 'MPG_%';

[User] Also, only show firms founded after the year 2010.

[Assistant] SELECT firm_name, website, managing_partner_id FROM law_firms WHERE managing_partner_id LIKE 'MPG_%' AND founded_date >= '2011-01-01';

[User] Just show the firm name and founded date, ordered by founded date ascending.

[Assistant] SELECT firm_name, founded_date FROM law_firms WHERE managing_partner_id LIKE 'MPG_%' AND founded_date >= '2011-01-01' ORDER BY founded_date ASC;

[User] List documents uploaded for cases of type 'Intellectual Property', showing the document name, upload timestamp, and the case number.

[Assistant] SELECT T1.document_name, T1.upload_timestamp, T2.case_number FROM documents AS T1 JOIN cases AS T2 ON T1.case_id = T2.case_id WHERE T2.case_type = 'Intellectual Property';

[User] Only include documents with a version greater than 1 and order by upload timestamp descending.

[Assistant] SELECT T1.document_name, T1.upload_timestamp, T2.case_number FROM documents AS T1 JOIN cases AS T2 ON T1.case_id = T2.case_id WHERE T2.case_type = 'Intellectual Property' AND T1.version > 1 ORDER BY T1.upload_timestamp DESC;

[User] List law firm names and the full name and specialization of all lawyers hired after 2020.

[Assistant] SELECT T1.firm_name, T2.first_name || ' ' || T2.last_name AS lawyer_full_name, T2.specialization FROM law_firms AS T1 JOIN lawyers AS T2 ON T1.firm_id = T2.firm_id WHERE T2.hire_date >= '2021-01-01'

[User] Only include firms founded before 2015.

[Assistant] SELECT T1.firm_name, T2.first_name || ' ' || T2.last_name AS lawyer_full_name, T2.specialization FROM law_firms AS T1 JOIN lawyers AS T2 ON T1.firm_id = T2.firm_id WHERE T2.hire_date >= '2021-01-01' AND T1.founded_date < '2015-01-01'

[User] Display only the firm name, lawyer full name, and hire date.

[Assistant] SELECT T1.firm_name, T2.first_name || ' ' || T2.last_name AS lawyer_full_name, T2.hire_date FROM law_firms AS T1 JOIN lawyers AS T2 ON T1.firm_id = T2.firm_id WHERE T2.hire_date >= '2021-01-01' AND T1.founded_date < '2015-01-01'

[User] Retrieve the names and upload timestamps of all documents of type 'Contract' that were uploaded between '2024-03-01' and '2024-03-31'.

[Assistant]
SELECT document_name, upload_timestamp
FROM legal_services.documents
WHERE document_type = 'Contract'
  AND upload_timestamp BETWEEN '2024-03-01' AND '2024-03-31';

[User] List all clients along with their case_number and case_type for cases that are currently 'Open'.

[Assistant]
SELECT c.first_name, c.last_name, c.email, cs.case_number, cs.case_type
FROM legal_services.clients AS c
JOIN legal_services.cases AS cs
  ON c.client_id = cs.client_id
WHERE cs.status = 'Open';


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.service_locations (
    location_id character varying(64) NOT NULL, -- unique identifier for the physical location
    agency_id character varying(64) NOT NULL, -- FK to agencies table
    location_name character varying(200), -- e.g., Downtown DMV Office
    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, -- description of opening times
    contact_phone character varying(32),
    is_accessible boolean, -- accessibility information (e.g., wheelchair access)
    PRIMARY KEY (location_id)
)

[User] Find all service locations in the city of 'Albany' that are accessible. Show their IDs, names, and contact phone numbers along with their address.

[Assistant] SELECT location_id, location_name, contact_phone, address FROM government_services.service_locations WHERE city = 'Albany' AND is_accessible = TRUE;

[User] List the names and cities of all service locations, along with the agency ID, where the locations are marked as accessible.

[Assistant] SELECT location_name, city, agency_id FROM government_services.service_locations WHERE is_accessible = TRUE;

[User] Can you also include the state for each location and sort the results by city alphabetically?

[Assistant] SELECT location_name, city, state, agency_id FROM government_services.service_locations WHERE is_accessible = TRUE ORDER BY city ASC;

[User] Find all service locations whose postal code starts with '75' and display their names, cities, and operating hours, including the agency ID.

[Assistant] SELECT location_name, city, operating_hours, agency_id FROM government_services.service_locations WHERE postal_code LIKE '75%';

[User] How many service locations do we have in each state?

[Assistant] SELECT state, COUNT(*) AS location_count FROM government_services.service_locations GROUP BY state;

[User] Only show states where there are at least 3 locations.

[Assistant] SELECT state, COUNT(*) AS location_count FROM government_services.service_locations GROUP BY state HAVING COUNT(*) >= 3;

[User] Can you also show the number of accessible locations in each of those states?

[Assistant] SELECT state, COUNT(*) AS location_count, SUM(CASE WHEN is_accessible = TRUE THEN 1 ELSE 0 END) AS accessible_location_count FROM government_services.service_locations GROUP BY state HAVING COUNT(*) >= 3;

[User] Order the results by accessible location count in descending order.

[Assistant] SELECT state, COUNT(*) AS location_count, SUM(CASE WHEN is_accessible = TRUE THEN 1 ELSE 0 END) AS accessible_location_count FROM government_services.service_locations GROUP BY state HAVING COUNT(*) >= 3 ORDER BY accessible_location_count DESC;

[User] List all states where we have more than two service locations, and display the number of locations per state.

[Assistant] SELECT state, COUNT(*) AS location_count FROM government_services.service_locations GROUP BY state HAVING COUNT(*) > 2;

[User] Can you also show only those states that have at least one accessible location?

[Assistant] SELECT state, COUNT(*) AS location_count FROM government_services.service_locations WHERE state IN (SELECT DISTINCT state FROM government_services.service_locations WHERE is_accessible = TRUE) GROUP BY state HAVING COUNT(*) > 2;

[User] Now sort the results by location_count in descending order.

[Assistant] SELECT state, COUNT(*) AS location_count FROM government_services.service_locations WHERE state IN (SELECT DISTINCT state FROM government_services.service_locations WHERE is_accessible = TRUE) GROUP BY state HAVING COUNT(*) > 2 ORDER BY location_count DESC;

[User] What if I only want states where more than one third of locations are accessible? Show state, location_count, and accessible_location_count.

[Assistant] SELECT state, COUNT(*) AS location_count, SUM(CASE WHEN is_accessible = TRUE THEN 1 ELSE 0 END) AS accessible_location_count FROM government_services.service_locations GROUP BY state HAVING SUM(CASE WHEN is_accessible = TRUE THEN 1 ELSE 0 END) > COUNT(*)/3;

[User] Show me a list of all appointment IDs, the name of the service associated with each appointment, and the location name where it is scheduled.

[Assistant]
SELECT appt.appointment_id, srv.service_id, loc.location_name
FROM government_services.appointments appt
JOIN government_services.service_locations loc ON appt.location_id = loc.location_id
JOIN government_services.applications appl ON appl.citizen_id = appt.citizen_id AND appl.service_id = appt.service_id
JOIN government_services.applications app ON app.service_id = appt.service_id
JOIN government_services.service_locations sloc ON appt.location_id = sloc.location_id;

[User] Actually, can you also include the scheduled start time for each appointment in the result?

[Assistant]
SELECT appt.appointment_id, srv.service_id, loc.location_name, appt.scheduled_start_time
FROM government_services.appointments appt
JOIN government_services.service_locations loc ON appt.location_id = loc.location_id
JOIN government_services.applications appl ON appl.citizen_id = appt.citizen_id AND appl.service_id = appt.service_id
JOIN government_services.applications app ON app.service_id = appt.service_id
JOIN government_services.service_locations sloc ON appt.location_id = sloc.location_id;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE web3.token_transfers ( transfer_id text PRIMARY KEY, token_id text, from_address text, to_address text, value numeric, transaction_id text, log_index int )

[User] Provide the count of transfers for each token_id.

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

[User] Actually, also include the total transferred value for each token_id.

[Assistant]
SELECT token_id,
       COUNT(*) AS transfer_count,
       SUM(value) AS total_transferred_value
FROM web3.token_transfers
GROUP BY token_id;

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

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

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

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

[User] Find all addresses that have only sent tokens (appear in from_address) but have never received any (do not appear in to_address).

[Assistant] SELECT DISTINCT from_address FROM web3.token_transfers WHERE from_address NOT IN (SELECT DISTINCT to_address FROM web3.token_transfers);

[User] For these addresses that have only sent tokens, show the total value of tokens each has sent.

[Assistant] SELECT t1.from_address, SUM(t1.value) AS total_sent_value FROM web3.token_transfers AS t1 WHERE t1.from_address NOT IN (SELECT DISTINCT to_address FROM web3.token_transfers) GROUP BY t1.from_address;

[User] List the top 5 addresses that have received the most token transfers.

[Assistant] SELECT to_address, COUNT(*) AS transfer_count FROM web3.token_transfers GROUP BY to_address ORDER BY transfer_count DESC LIMIT 5;

[User] Okay, but only for token_id '0xabc123...' and also show the total value received by each of these addresses for that token.

[Assistant] SELECT to_address, COUNT(*) AS transfer_count, SUM(value) AS total_received_value FROM web3.token_transfers WHERE token_id = '0xabc123...' GROUP BY to_address ORDER BY transfer_count DESC LIMIT 5;

[User] Show me the top 10 token transfers by value, including the token ID and the transaction ID, sorted in descending order.

[Assistant] SELECT token_id, transaction_id, value FROM web3.token_transfers ORDER BY value DESC LIMIT 10;

[User] Which transaction_id has the highest total value transferred? Show the transaction_id and the sum of values for that transaction.

[Assistant] SELECT transaction_id, SUM(value) AS total_transaction_value FROM web3.token_transfers GROUP BY transaction_id ORDER BY total_transaction_value DESC LIMIT 1;


System:
You are an expert in writing database language. You can write a corresponding database language query to answer the user's question based on the table structure described by the table creation statement.
##Table Structure
CREATE TABLE transportation.locations ( location_id text PRIMARY KEY, name text, type text, address_line1 text, city text, state_province text, postal_code text, country text, latitude numeric, longitude numeric, timezone text )

[User] List all locations situated within the state of California.

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

[User] Now, refine this list to only include locations that are specifically in Los Angeles.

[Assistant] SELECT location_id, name, city, state_province FROM transportation.locations WHERE state_province = 'CA' AND city = 'Los Angeles';

[User] Could you also include the type of location and its postal code in the result?

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

[User] Finally, order these locations by their name in alphabetical order.

[Assistant] SELECT location_id, name, city, state_province, type, postal_code FROM transportation.locations WHERE state_province = 'CA' AND city = 'Los Angeles' ORDER BY name;

[User] Show me all locations in New York with latitude above 40.7, including their type and coordinates.

[Assistant] SELECT name, type, latitude, longitude FROM transportation.locations WHERE state_province = 'New York' AND latitude > 40.7;

[User] There's a typo in your SQL - it should be 'locations' not 'locatons'. Also, can you include the city and order by latitude in descending order?

[Assistant] SELECT name, type, city, latitude, longitude FROM transportation.locations WHERE state_province = 'New York' AND latitude > 40.7 ORDER BY latitude DESC;

[User] Now filter these results to only show locations of type 'gas station' or 'depot' and include their postal codes.

[Assistant] SELECT name, type, city, postal_code, latitude, longitude FROM transportation.locations WHERE state_province = 'New York' AND latitude > 40.7 AND type IN ('gas station', 'depot') ORDER BY latitude DESC;

[User] Can you show me the name, city, and type for all locations that are in the same city but have different types?

[Assistant] SELECT l1.name, l1.city, l1.type FROM transportation.locations l1 JOIN transportation.locations l2 ON l1.city = l2.city AND l1.location_id <> l2.location_id AND l1.type <> l2.type;

[User] Please only include locations where the city is 'Chicago'.

[Assistant] SELECT l1.name, l1.city, l1.type FROM transportation.locations l1 JOIN transportation.locations l2 ON l1.city = l2.city AND l1.location_id <> l2.location_id AND l1.type <> l2.type WHERE l1.city = 'Chicago';

[User] Find all cities that contain at least one location of type 'Depot' and at least one location of type 'Station'.

[Assistant] SELECT city FROM transportation.locations WHERE type IN ('Depot', 'Station') GROUP BY city HAVING COUNT(DISTINCT CASE WHEN type = 'Depot' THEN location_id END) > 0 AND COUNT(DISTINCT CASE WHEN type = 'Station' THEN location_id END) > 0;

[User] Can you give me all locations in Los Angeles?

[Assistant]
SELECT location_id, name, type, address_line1, city, state_province, postal_code, country, latitude, longitude, timezone
FROM transportation.locations
WHERE city = 'Los Angeles';

[User] I want to see only locations of type 'Depot' in Los Angeles.

[Assistant]
SELECT location_id, name, type, address_line1, city, state_province, postal_code, country, latitude, longitude, timezone
FROM transportation.locations
WHERE city = 'Los Angeles' AND type = 'Depot';

[User] Can you show me their postal codes and sort them by name in ascending order?

[Assistant]
SELECT location_id, name, postal_code
FROM transportation.locations
WHERE city = 'Los Angeles' AND type = 'Depot'
ORDER BY name ASC;

[User] Actually, I also want to see the state_province in the output.

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

[User] Find all distinct pairs of locations that are located in the same city. List their 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 AS l1 JOIN transportation.locations AS l2 ON l1.city = l2.city AND l1.location_id < l2.location_id;