get count of subjects with at least one record in posts table I have two tables: posts and subjects.

posts may have subjects, but not all subjects may have been assigned to some posts. Now I want to count only those subjects with at least one post related to them.

subject columns are: id, name
posts columns are: id, title, subject_id
Try:

select count(*) from subjects where exists (select 1 from posts where subjects.id = posts.subject_id);