Introduction
A scalar subquery in SELECT lets you get a single value from another table or query to use in each row of your main query. It helps add extra info without joining tables.
Jump into concepts and practice - no test required
SELECT column1, (SELECT single_value FROM table2 WHERE condition) AS alias_name FROM table1;
SELECT name, (SELECT MAX(score) FROM tests WHERE tests.student_id = students.id) AS max_score FROM students;
SELECT product_name, (SELECT COUNT(*) FROM sales WHERE sales.product_id = products.id) AS total_sales FROM products;
SELECT employee_name, (SELECT department_name FROM departments WHERE departments.id = employees.department_id) AS dept FROM employees;
CREATE TABLE employees (id INT, name VARCHAR(20), department_id INT); CREATE TABLE departments (id INT, department_name VARCHAR(20)); INSERT INTO employees VALUES (1, 'Alice', 10), (2, 'Bob', 20), (3, 'Charlie', 10); INSERT INTO departments VALUES (10, 'HR'), (20, 'Sales'); SELECT name, (SELECT department_name FROM departments WHERE departments.id = employees.department_id) AS department FROM employees ORDER BY id;
SELECT clause return?SELECT clause?employees(id, name, dept_id) and departments(id, dept_name), what is the output of this query?SELECT name, (SELECT dept_name FROM departments WHERE id = employees.dept_id) AS department FROM employees ORDER BY name;
SELECT name, (SELECT dept_name FROM departments WHERE id = employees.dept_id) AS department FROM employees WHERE (SELECT COUNT(*) FROM departments) > 0;
Options:
A) SELECT product_name, IFNULL((SELECT category_name FROM categories WHERE id = products.category_id), 'Uncategorized') AS category FROM products WHERE category_id IS NOT NULL;
B) SELECT product_name, (SELECT category_name FROM categories WHERE id = products.category_id) OR 'Uncategorized' AS category FROM products;
C) SELECT product_name, (SELECT category_name FROM categories WHERE id = products.category_id) AS category FROM products WHERE category_id IS NOT NULL;
D) SELECT product_name, COALESCE((SELECT category_name FROM categories WHERE id = products.category_id), 'Uncategorized') AS category FROM products;