You can fix this in either of the two ways, Option 1: Use LIMIT clause at the end of the SOQL so as to ensure the number of rows returned by SOQL do not exceed the limit for e.g. [SELECT Id FROM Account LIMIT 10] This will limit the returned rows to 10.
Option 2: Put additional criteria in WHERE clause to ensure number of returned rows are always less than 50K. for e.g. [SELECT Id FROM Account WHERE Industry = 'Agriculture'] assuming there are no more than 50K account records in your org.
Note: The governor limit considers cumulative number of rows returned in one transaction. So if you have 2 SOQL query running in same transaction and both return 30K records then you'll still encounter the query rows exception.
You can fix this in either of the two ways,
Option 1: Use LIMIT clause at the end of the SOQL so as to ensure the number of rows returned by SOQL do not exceed the limit
for e.g. [SELECT Id FROM Account LIMIT 10] This will limit the returned rows to 10.
Option 2: Put additional criteria in WHERE clause to ensure number of returned rows are always less than 50K.
for e.g. [SELECT Id FROM Account WHERE Industry = 'Agriculture'] assuming there are no more than 50K account records in your org.
Note: The governor limit considers cumulative number of rows returned in one transaction. So if you have 2 SOQL query running in same transaction and both return 30K records then you'll still encounter the query rows exception.
Convert into a batch mode or limit the number of rows by adding qualifying WHERE conditions which reduce the record count.