# Write a SOQL query to find all LoginHistory records for a specific User in the last 24 hours where the login status failed.

**Topic:** Development · **Difficulty:** Medium · **Asked at:** PwC, EY, KPMG · **Tags:** soql, scenario, login-history, audit

Read it on the site: https://www.forcechallenges.com/interview-questions/write-a-soql-query-to-find-all-loginhistory-records-for-a-specific-user-in-the-last-24-hours-where-the-login

## Answer

Filter `LoginHistory` by user, time window and non-success status.

```apex
Datetime since = Datetime.now().addHours(-24);
List<LoginHistory> failed = [
    SELECT UserId, LoginTime, Status, SourceIp, LoginType, Application
    FROM LoginHistory
    WHERE UserId = :userId AND LoginTime >= :since AND Status != 'Success'
    ORDER BY LoginTime DESC
];
```
Using a datetime bind variable is the reliable way to express "last 24 hours", since date literals work in whole days.

---
Source: ForceChallenges · last updated 2026-10-19
