The comma can come before "which" depending on whether you want to introduce a restrictive (essential information) or non-restrictive clause (non-essential information)
(1) Restrictive clause:
The house which I lived in two years ago was made of bricks(2) Non-restrictive clause:
The house, which I lived in two years ago, was made of bricksIn (1), the emphasis is on
that house where I lived two years ago. Thus, what comes after "which" is essential and there is no comma to separate it from the rest of the sentence
In (2), the emphasis is put on
a house made of bricks, any house made of bricks. Thus, you can remove the portion which comes between the commas and the sentence makes sense.
Let's look at my sentence again.
In red is a parenthetical element which, if removed, does not affect the meaning of the sentenceThe comma in this case comes after "which" here introduces a parenthetical element (non-essential information) but is not part of the clause which includes "which". Let's remove that parenthetical element and analyze the sentence again.
In red is a parenthetical element which does not affect the meaning of the sentenceThe portion in red is now part of the
restrictive clause introduced by "which" and this is essential information as there is no comma which comes before "which". Thus, my intention while writing that sentence was to put an emphasis on the restrictive clause which comes after "parenthetical element" and to describe to you what it really is.
On a final note, remember that while "which" can introduce either a restrictive or non-restrictive clause, "that" will NEVER introduce a non-restrictive clause but will ALWAYS introduce a restrictive clause. Therefore, you will NEVER have a comma preceding "that" in a sentence.
For example
(1) Non-restrictive clause: The house, that I lived in two years ago, was made of bricks --> wrong!
(2) Restrictive clause: The house that I lived in two years ago was made of bricks --> right