244 views
CREATE TABLE staff ( id TEXT name TEXT head_id TEXT ); id | name | head_id -------------------- 1 | Ivan | NULL 2 | Petr | 1 3 | Alice | 1 4 | Max | 2 5 | Alex | 2 6 | Elena | 4 7 | Bob | NULL Expected output: employee_name | manager_name --------------------------- Ivan | NULL Petr | Ivan Alice | Ivan Max | Petr Alex | Petr Elena | Max Bob | NULL SELECT e.name AS employee_name, m.name AS manager_name FROM staff e LEFT JOIN staff m ON e.head_id = m.id
Asked at
AI answer
In the provided SQL query example, it correctly implements the output of a list of employees and their managers from a single staff table using a self JOIN.
The staff table contains fields id, name, and head_id, where head_id is a reference to the id of the employee's manager.
Query:
SELECT e.name AS employee_name, m.name AS manager_name
FROM staff e
LEFT JOIN staff m ON e.head_id = m.id
eis an alias for employees.mis an alias for their managers.- LEFT JOIN ensures that even employees without a manager (for example, Ivan and Bob) will have a row with
manager_name= NULL.
Thus, the query outputs the names of employees and their managers if they exist, which matches the expected result.
Also asked at plata
- What are your salary expectations?
- [name] asked: Are you still working at your current company? Why did you decide to leave?
- What delivery guarantees does Kafka have? What needs to be done on the producer to achieve exactly-once?
- [name] asked: Tell me about your current workplace — what kind of company is it, what product are you working on?
- If the EXPLAIN estimate significantly differs from EXPLAIN ANALYZE — what does it mean?
Similar questions
- How does LEFT JOIN work? Which table is used for what?
- How do the field values from the right table behave in the result of a LEFT JOIN when there are no matching records in it?
- SELECT u.id, u.name, o.id as order_id, o.amount FROM users u ? JOIN orders o ON u.id = o.user_id;
- If you replace LEFT JOIN with a regular JOIN in the user query, but leave WHERE p.id IS NULL, what will be returned?
- Given the table: | name | lang | |------|------| | Nick | C# | | Nick | SQL | | Eva | Rust | | Eva | C# | | Vika | SQL | | Ivan | Java | | Ivan | SQL | Write a query that selects the names of employees who know SQL and at least one other language. Assume one employee is one name.