We need to use the Dynamic ManagementObject(DMO) sys.dm_db_index_physical_stats. This DMO accepts 5 parameters : DatabaseID, ObjectID, IndexID, PartitionNumber and Mode.
Generally when we need to check fragmentation we use the DB_ID with Detailed mode. There are 3 Columns to look out for
1. avg_fragmentation_in_percent : Number of out of order pages in the index - Lower value is better
2. fragment_count : Number of fragments in an index(Continuous Pages) - Lower value is better
3. avg_fragment_size_in_pages : Average Number of pages in one fragment - Larger value is better
If the avg_fragmentation_in_percent is greater than 30, then we should use Rebuild Index and if the avg_fragmentation_in_percent is less than 30, then we should use Reorganize Index.
SELECT D.NAME AS DBNAME,OBJECT_NAME(A.object_id) AS TABLENAME, B.name AS INDEXNAME, *
FROM SYS.dm_db_index_physical_stats(DB_ID(),OBJECT_ID('TABLE_NAME'),NULL,NULL,'DETAILED') A
CROSS APPLY(
SELECT NAME FROM SYS.INDEXES WHERE OBJECT_ID = A.object_id AND index_id IN(A.index_id))B
INNER JOIN SYS.DATABASES D ON A.database_id= D.database_id
In the above query you can replace Object_ID parameter with NULL to get the details about all the tables. And then can run the Alter Index query for the individual Index or for all the Indexes.
ALTER INDEX INDEX_NAME ON TABLE_NAME REORGANIZE/REBUILD
ALTER INDEX ALL ON TABLE_NAME REORGANIZE/REBUILD