You need to redirect any non-empty URL-path OR the homepage (empty URL-path) with a query string. You should also remove the query string as part of the redirect (your rule currently preserves the query string from the initial request).
For example, try the following instead:
# Redirect everything to the homepage (same domain)
RewriteCond %{REQUEST_URI} ^/. [OR]
RewriteCond %{QUERY_STRING} .
RewriteRule ^ http://www.example.com/ [QSD,R=301,L]
The above states... for all URL-paths where the URL-path consists of at least one character (after the initial slash) OR contains a query string then redirect to the root.
The QSD
flag discards the original query string from the request.
The NC
flag on the rule is superfluous, since you aren't matching specific letters anyway.
Aside: However, I would question the motives for doing something like this. Search engines (Google) will see mass redirects to the homepage as soft-404s, so there is no SEO benefit in doing this and it can often be confusing for users if they are following a link that previously existed. A meaningful 404 response is usually the preferred option in this scenario.
UPDATE:
If i would like to use this code also to redirect to other domain what should i change or add to redirect also main page?
Assuming the other domain also points to a different server then you just need to remove the two conditions on the above rule to redirect everything and remove the query string.
For example:
# Redirect everything to the homepage on an external domain
RewriteRule ^ http://www.example.com/ [QSD,R=301,L]