Q:

Count number of foreign key values referred

I have two tables. Table 1 and Table 2. 
id2 in Table 2 is the foreign key of the primary key id1 in Table 1. 
How do I find if all the values of id1 column are used in id2 column?
If none of them are used, how many values of id1 are used in id2?

A:

Since you are only interested in finding out how many ids are used,
SELECT COUNT(table2.id2) FROM table1 LEFT JOIN table2 ON
table1.id = table2.id2

This is thanks to an often overlooked feature of COUNT, instead of COUNT(*) you can specify a column name and COUNT(column_name) will only count NOT NULL values of that column.

