What does Psalm 139:23 mean?
Although David despised the wicked who spoke against God and took His name in vain, he realized he was not perfect. He was keenly aware that sin might be lurking in his heart and mind. Therefore, he asked the Lord to search his heart and know his thoughts. The Hebrew word translated "search" here is one often used to describe the way miners searched deeply for gold. This is the same term used at the beginning of this psalm (Psalm 139:1), as well as of Israelites scouring the land for territory to claim as their own (Judges 18:2).David was a man after God's own heart (Acts 13:22), but he knew the heart is "deceitful above all things, and desperately sick" (Jeremiah 17:9). Only the omniscient God, whom he described earlier in the psalm, could search the heart (1 Samuel 16:7). David also asked the Lord to know his thoughts. Again, only the omniscient God could do this.
David wrote in Psalm 139:2 that God discerned his thoughts. Our thought lives matter. Thoughts form the seed bed of sin (James 1:14–15), therefore we ought to practice what Paul counseled in Philippians 4:8: "whatever is true, whatever is honorable, whatever is just, whatever is pure, whatever is lovely, whatever is commendable, if there is any excellence, if there is anything worthy of praise, think about these things."
Psalm 139:17–24 emphasizes God's justice. Prior sections of this psalm bore witness to God's omniscience (Psalm 139:1–6), His omnipresence (Psalm 139:7–12), and His omnipotence (Psalm 139:13–16). David rejoices in God's thoughts and nearness, but despises the wicked around him. He longs for God to slay them. He sees God's enemies as his own enemies, but is acutely aware of the possibility that sin dwells in him. Therefore, he asks God to search him and lead him in the way everlasting.
In this psalm David marvels at God's amazing characteristics. God knows everything about him: where he goes, all David's thoughts and everything about his conduct. The Lord knows what David will say even before David says it. There is no place David can go that God isn't already present. David marvels at God's creative work in the womb. He is thankful for God's innumerable thoughts for him and for God's presence day and night. Finally, David's thoughts turn to the wicked. He considers them God's enemies and his, and longs for God to slay them. David is disgusted by evil people because they rail against God and take His name in vain. He asks God to search his heart to see if any sin is there, and he asks God to lead him in the way everlasting.