Limit the query results: Get 3 Most Expensive Products
/*
mysql> select * from Product;
+-----------+------------+----------------------+-------+
| ProductID | Name | Description | Price |
+-----------+------------+----------------------+-------+
| 1 | Java | Java Demo Code | 6 |
| 2 | Swing | Swing Demo Code | 7 |
| 3 | C# | C# Demo Code | 4 |
| 4 | JavaScript | JavaScript Demo Code | 3 |
| 5 | SQL | SQL Demo Code | 8 |
| 6 | Struts | Struts Demo Code | 9 |
+-----------+------------+----------------------+-------+
6 rows in set (0.00 sec)
mysql> /* Get 3 Most Expensive Products*/
mysql> SELECT Name, Price
-> FROM Product
-> ORDER BY Price DESC, Name ASC
-> LIMIT 0,3;
+--------+-------+
| Name | Price |
+--------+-------+
| Struts | 9 |
| SQL | 8 |
| Swing | 7 |
+--------+-------+
3 rows in set (0.00 sec)
*/
/* Create Database */
Drop TABLE Product;
CREATE TABLE Product (
ProductID INT AUTO_INCREMENT NOT NULL PRIMARY KEY,
Name VARCHAR(50) NOT NULL,
Description VARCHAR(255) NOT NULL,
Price DECIMAL NULL
) Type=InnoDB;
/* Insert Data */
INSERT INTO Product (Name, Description, Price) VALUES ('Java',
'Java Demo Code',
5.99 );
INSERT INTO Product (Name, Description, Price) VALUES ('Swing',
'Swing Demo Code',
6.99 );
INSERT INTO Product (Name, Description, Price) VALUES ('C#',
'C# Demo Code',
3.99 );
INSERT INTO Product (Name, Description, Price) VALUES ('JavaScript',
'JavaScript Demo Code',
2.99 );
INSERT INTO Product (Name, Description, Price) VALUES ('SQL',
'SQL Demo Code',
7.99 );
INSERT INTO Product (Name, Description, Price) VALUES ('Struts',
'Struts Demo Code',
8.99 );
select * from Product;
/* Get 3 Most Expensive Products*/
SELECT Name, Price
FROM Product
ORDER BY Price DESC, Name ASC
LIMIT 0,3;
Related examples in the same category