SQL PRACTICE: SQL SERVER - Bottom N Records

  Q5. How to read last 5 records from a table using SQL?

N.B: I am using the following:

Database -> MSSQL

SQL Dialect -> T-SQL

Consider below employment table as a source data.

-- Create an employment table

create table employment(

EmpId int,

FirstName varchar(20),

LastName varchar(20),

Salary int

);

-- Insert values to the employment table

insert into employment(EmpId, FirstName, LastName, Salary)

Values

(100, 'Genet', 'Mathew', 40000),

(101, 'Mike', 'Mcarthy', 80000),

(102, 'Teddy', 'Arthur', 60000),

(103, 'Abrham', 'Zerai', 70000),

(104, 'Aman','Mike', 65000),

(105, 'Tedros','Haile', 50000),

(106, 'Abi', 'Jacob', 60000),

(107, 'Bruno', 'Yonus', 75000),

(108, 'Mathew', 'Samuel',60000),

(109, 'Rodas','Keyun', 65000),

(110, 'Mat', 'Joseph', 100000);

Select  * from employment;

Table 1. Employment Table

Ans: In SQL Server, the Top keyword is used to retrieve the most top records/values from a table.

In our case, to find the last 5 (any number of rows) records, we need to sort the empId column in descending order and get the top 5 records, that will return us the bottom rows.

Select  Top 5 * from employment

order by EmpId desc;


Table 2. Last 5 Records

Comments

Popular posts from this blog

SQL PRACTICE: SQL SERVER - DATEADD Function

SQL PRACTICE: SQL SERVER - Unique Records

SQL PRACTICE: SQL SERVER: DATEDIFF Function