Introduction
In this tutorial, you will learn about SQL queries and their equivalent Ecto queries. Both are used to interact with the database.
SQL
SQL stands for Structured Query Language, a language designed to interact with databases. We will explore the database used in this tutorial.
Database
The database for this tutorial, named sql_ecto_repo, is derived from the sql-sample-database and manages the HR data of a small business. It has 7 tables:
- The
employeestable stores the data of employees. - The
jobstable stores the job data including job title and salary range. - The
departmentstable stores department data. - The
dependentstable stores the employee’s dependents. - The
locationstable stores the location of the departments of the company. - The
countriestable stores the data of countries where the company is doing business. - The
regionstable stores the data of regions such as Asia, Europe, America, and the Middle East and Africa. The countries are grouped into regions.
The diagram below illustrates the tables in the sql_ecto_repo database.

The number of records in each table:
- employees - 31
- dependents - 30
- departments - 11
- jobs - 11
- locations - 7
- countries - 25
- regions - 4
Ecto
Ecto is an Elixir library that acts as a wrapper around the database, allowing us to interact with it. Ecto has four main components:
- Ecto.Schema - Defines the structure of our tables, including columns, data types, and relationships.
- Ecto.Repo - Handles database operations such as creating, deleting, updating, and querying records.
- Ecto.Query - Used to perform queries through Ecto.Repo.
- Ecto.Changeset - Sets constraints for columns, defines how values should be inserted, and allows casting of columns
Our repo is named as Hr.Repo. You can explore the schema structure used in this tutorial on GitHub.
Every SQL query has its equivalent Ecto query and vice versa. Let's explore some SQL queries and their Ecto counterparts in this tutorial.