How to selecet the last row of a database
时间: 2024-10-19 10:05:48 浏览: 6
To select the last row from a database, the method varies depending on the database management system (DBMS) you are using. Here are some common approaches:
1. **SQL (Structured Query Language)**:
- For MySQL and PostgreSQL: Use the LIMIT clause with an OFFSET.
```sql
SELECT * FROM table_name
ORDER BY id DESC
LIMIT 1;
```
- In SQLite, since there's no built-in `OFFSET`, you might need to count rows first.
```sql
SELECT * FROM (SELECT * FROM table_name ORDER BY id DESC LIMIT 1) subquery
```
2. **SQL Server**:
```sql
SELECT TOP 1 * FROM table_name ORDER BY id DESC;
```
3. **Oracle**:
```sql
SELECT * FROM (
SELECT ROW_NUMBER() OVER (ORDER BY id DESC) AS row_num, *
FROM table_name
) WHERE row_num = 1;
```
4. **Microsoft Access (VBA SQL Query)**:
```vba
Dim sql As String
sql = "SELECT * FROM table_name ORDER BY ID DESC LIMIT 1"
' Execute the query using DAO or ADODB libraries
```
5. **NoSQL databases like MongoDB**:
```javascript
db.collection.find().sort({ _id: -1 }).limit(1);
```
Remember to replace `table_name` and `id` with your actual table name and primary key column.
阅读全文