Bài 6
Home

Sắp xếp dữ liệu

ORDER BY để sắp xếp kết quả

TargetMục tiêu học tập

  • Sử dụng ORDER BY để sắp xếp
  • ASC (tăng dần) vs DESC (giảm dần)
  • Sắp xếp theo nhiều cột

Lesson 6: Sắp Xếp Dữ Liệu

ORDER BY cơ bản

ASC - Tăng dần (mặc định)

-- Sản phẩm từ rẻ đến đắt
SELECT product_name, unit_price
FROM products
ORDER BY unit_price ASC;

DESC - Giảm dần

-- Sản phẩm từ đắt đến rẻ
SELECT product_name, unit_price
FROM products
ORDER BY unit_price DESC
LIMIT 10;

Sắp xếp theo nhiều cột

-- Sắp xếp theo category trước, sau đó theo price
SELECT c.category_name, p.product_name, p.unit_price
FROM products p
JOIN categories c ON p.category_id = c.category_id
ORDER BY c.category_name ASC, p.unit_price DESC;

Ví dụ thực tế

-- Top 10 giao dịch lớn nhất
SELECT sale_date, total_amount, payment_method
FROM sales
ORDER BY total_amount DESC
LIMIT 10;

-- Doanh thu theo cửa hàng (cao xuống thấp)
SELECT st.store_name, SUM(s.total_amount) as revenue
FROM sales s
JOIN stores st ON s.store_id = st.store_id
GROUP BY st.store_name
ORDER BY revenue DESC;
Home

SQL Editor

Loading...
Clipboard

Bài tập thực hành

Bài tập 1: Sắp xếp khách hàng theo tên (A-Z)

HintGợi ý

ORDER BY customer_name ASC

CheckXem đáp án
SELECT customer_name, city, phone
FROM customers
ORDER BY customer_name ASC;

Bài tập 2: Top 5 sản phẩm đắt nhất

HintGợi ý

ORDER BY unit_price DESC LIMIT 5

CheckXem đáp án
SELECT product_name, unit_price, brand
FROM products
ORDER BY unit_price DESC
LIMIT 5;

Bài tập 3: Cửa hàng có doanh thu thấp nhất (hiện 3 cửa hàng)

HintGợi ý

GROUP BY, SUM, ORDER BY ASC

CheckXem đáp án
SELECT st.store_name, SUM(s.total_amount) as revenue
FROM sales s
JOIN stores st ON s.store_id = st.store_id
GROUP BY st.store_name
ORDER BY revenue ASC
LIMIT 3;
HomeTrang chủ

Đang tải schema...

Bài 6: Sắp xếp dữ liệu - Học SQL | Data Bình Dân