Posts

Showing posts from 2020

SQL WHERE and HAVING clause (with examples)

Image
In SQL, there is two clause used for filtering: WHERE and HAVING . Most of the time WHERE clause is sufficient. However, the reason why HAVING clause exist is because WHERE clause cannot filter aggregates. To show an example of how each clause can be used, let's say we are running an ice cream company. We produce several flavours of ice cream. We sell these ice creams to stores in multiple countries. Each store would have different stocks of our ice cream varieties. Our users are from all over the world. From that example, we have the following schema of the database. In the following section, I will show some examples for both clauses in PostgreSQL . I have created the database dump  so you can experiment with it yourself. WHERE clause We can use the WHERE clause to search stores that is available in a county with the following query. SELECT * FROM stores WHERE country = 'ID'; We can also use it to find users who cannot access o