BigQuery SQL Cheat Sheet with Visual Explanations
1. SELECT Query
The SELECT statement is used to fetch data from a table. You can select specific columns or all (*) columns. Here's an
example with employee data.
SELECT name, age FROM `company.hr.employees`;
2. WHERE Clause
The WHERE clause filters records based on a condition. For example, selecting employees older than 30.
SELECT * FROM `company.hr.employees`
WHERE age > 30;
3. GROUP BY with Aggregation
Use GROUP BY to aggregate values per group. Here, we count the number of employees in each department.
SELECT department, COUNT(*) AS total
FROM `company.hr.employees`
GROUP BY department;
4. JOINs
JOIN combines rows from two or more tables based on a related column. Here's an inner join between employees and
departments.
SELECT e.name, d.department_name
FROM `company.hr.employees` e
JOIN `company.hr.departments` d
ON e.department_id = d.department_id;
5. CTE (WITH clause)
CTEs simplify complex queries. This example gets the average salary by department, then filters high-paying ones.
WITH avg_salary AS (
SELECT department, AVG(salary) AS avg_sal
FROM `company.hr.employees`
GROUP BY department
)
SELECT * FROM avg_salary
WHERE avg_sal > 50000;
6. UNNEST Arrays
BigQuery supports ARRAY types. UNNEST is used to flatten an array column, like a list of skills per employee.
SELECT name, skill
FROM `company.hr.employees`, UNNEST(skills) AS skill;