MySQL
SQL Query
Database Management
Joins
Data Retrieval

MySQL: select all columns from one table and some from another

Codemia Knowledge Hub ·

Join the two tables and qualify the wildcard with a table alias: SELECT e.*, d.department returns every column from employees and only department from departments. You can also combine tables with sub-queries or UNION, but a JOIN is the right fit when the rows are related by a column.

SELECT basics

The basic SELECT format:

sql
SELECT column1, column2, ...
FROM table_name;

An asterisk (*) selects all columns:

sql
SELECT * FROM table_name;

Selecting e.* plus specific columns with a JOIN

A JOIN combines rows from two or more tables based on a related column. The most common types are INNER JOIN and LEFT JOIN.

INNER JOIN example

Take two tables:

  1. employees - Stores employee information.
  2. departments - Stores department information.
sql
1-- `employees` table
2+----+----------+-----------+
3| id | name     | dept_id   |
4+----+----------+-----------+
5| 1  | Alice    | 101       |
6| 2  | Bob      | 102       |
7| 3  | Charlie  | 103       |
8+----+----------+-----------+
9
10-- `departments` table
11+----+------------+
12| id | department |
13+----+------------+
14| 101| HR         |
15| 102| Sales      |
16| 103| IT         |
17+----+------------+

To get all columns from employees and only the department name from departments:

sql
SELECT e.*, d.department
FROM employees e
INNER JOIN departments d ON e.dept_id = d.id;

LEFT JOIN example

A LEFT JOIN returns all records from the left table (employees) and the matched records from the right table (departments). Where there is no match, the right table's columns are NULL.

sql
SELECT e.*, d.department
FROM employees e
LEFT JOIN departments d ON e.dept_id = d.id;

This includes every employee, even one with no matching department.

How the query works

  1. Aliases: employees and departments get the aliases e and d for readability.
  2. Wildcard selector (*): e.* selects all columns from employees.
  3. Specific columns: d.department selects only the department column from departments.
  4. JOIN condition: the ON clause specifies how the tables relate (e.dept_id = d.id).
ConceptDescription
SELECT ColumnsUse the asterisk * to select all columns, or specify columns explicitly.
JOIN TypesINNER JOIN returns matching rows; LEFT JOIN returns all left-side rows.
AliasesTables and columns can be given temporary names for clarity.
ON ClauseSpecifies how tables are related, ensuring relational data retrieval.

Course
Beginner
27 lessons
10 hours
System Design Fundamentals

Build a strong foundation in designing scalable, reliable distributed systems.

View the course
System Design practice on Codemia

Work through 120+ system design problems with detailed solutions, from rate limiters to multi-region storage.

Practice system design