How could David be so certain of his own righteousness? (Psalm 18:20–24)
In the Old Testament, Israel could know God’s moral will for his people through the laws set forth in the covenant made at Mount Sinai (Ex 20:1—24:18; Lev 26:1–46; Dt 4:1—11:32). If David lived in a manner consistent with those covenant stipulations, he could legitimately speak of his righteousness.
David was not perfect by any means—a fact he readily acknowledged (Ps 51:1–19). But while it is a great sin to violate God’s law, the covenant provided a means by which confession, repentance, restitution and restoration to God and the community could take place. The sacrificial system outlined in Leviticus 1:1—7:38 provided the Israelites with a process by which to make amends to God and their neighbors when they sinned. But more important than sacrifice is a humble and penitent heart that casts itself entirely on the mercy of God (Ps 51:1,16–17). When we do this, God “imputes” righteousness to us—that is, he credits the perfect righteousness of Jesus Christ to us (2Co 5:21).
Taken from NIV Quest Study Bible