To get the last 10 rows from a table in SQL, the approach you take depends on the database system you are using (e.g., MySQL, PostgreSQL, SQL Server, etc.). Here's how you can do it in different SQL dialects:
1. MySQL or MariaDB
In MySQL or MariaDB, you can use the ORDER BY clause to sort the data in descending order and then use LIMIT to fetch the last 10 rows:
SELECT *
FROM your_table
ORDER BY your_column DESC
LIMIT 10;
If you want to preserve the order of the rows as they were inserted (ascending order of your_column), you can reverse the order:
SELECT *
FROM your_table
ORDER BY your_column DESC
LIMIT 10
2. PostgreSQL
PostgreSQL has a similar syntax to MySQL. You can use ORDER BY and LIMIT:
SELECT *
FROM your_table
ORDER BY your_column DESC
LIMIT 10;
Again, the idea is to reverse the sorting order and use LIMIT to retrieve the desired number of rows.
3. SQL Server
In SQL Server, you can use TOP along with ORDER BY to get the last 10 rows:
SELECT TOP 10 *
FROM your_table
ORDER BY your_column DESC;
If you want to preserve the original order, you might need to use a subquery:
SELECT *
FROM (
SELECT *
FROM your_table
ORDER BY your_column DESC
) AS subquery
ORDER BY your_column ASC;
4. Oracle SQL
In Oracle SQL, you can use the ROWNUM or FETCH method to retrieve the last 10 rows. Here's an example using ROWNUM:
SELECT *
FROM (
SELECT *
FROM your_table
ORDER BY your_column DESC
)
WHERE ROWNUM <= 10;
Alternatively, with FETCH (in newer versions of Oracle):
SELECT *
FROM your_table
ORDER BY your_column DESC
FETCH FIRST 10 ROWS ONLY;
General Notes:
your_column: This should be a column that allows you to define the "order" of the rows (usually a date, ID, or timestamp). Without this, SQL won't have a way to determine which rows are "last".- Ascending or Descending: Use
DESC(descending) to get the last rows when ordered by a column like an ID or timestamp. If you want the rows in their original order, you may need to apply another sort.
Let me know if you need further clarification or adjustments based on your specific database!
No comments:
Post a Comment