diff --git a/changelog.d/12977.feature b/changelog.d/12977.feature
new file mode 100644
index 0000000000000000000000000000000000000000..3c73363d28d284f581d620157c8b7d41c30c1ca2
--- /dev/null
+++ b/changelog.d/12977.feature
@@ -0,0 +1 @@
+Add new `media_retention` options to the homeserver config for routinely cleaning up non-recently accessed media.
\ No newline at end of file
diff --git a/synapse/storage/databases/main/media_repository.py b/synapse/storage/databases/main/media_repository.py
index 3c585c555ad3c3974298eb58cb15ee1181aa8abd..d028be16de819faecf3289e883970866a5b099e1 100644
--- a/synapse/storage/databases/main/media_repository.py
+++ b/synapse/storage/databases/main/media_repository.py
@@ -327,7 +327,7 @@ class MediaRepositoryStore(MediaRepositoryBackgroundUpdateStore):
         if include_protected_media is False:
             # Do not include media that has been protected from quarantine
             sql += """
-                AND safe_from_quarantine = false
+                AND NOT safe_from_quarantine
             """
 
         def _get_local_media_ids_txn(txn: LoggingTransaction) -> List[str]: