Correlated queries are queries in which the subquery references a column from the outer query. The subquery is evaluated for each row processed by the outer query, taking into account the values from the outer query. This allows the subquery to be correlated or connected to the outer query.
Correlated queries are useful when performing operations based on related data between two or more tables. They can help us retrieve data that depends on the values of the current row being processed in the outer query.
Here’s an example of a correlated query in MySQL:
SELECT column1FROM table1 t1WHERE column1 > (SELECT AVG(column2)FROM table2 t2WHERE t2.foreign_key = t1.key);
In this example, the subquery (SELECT AVG(column2) FROM table2 t2 WHERE t2.foreign_key = t1.key)
is correlated to the outer query. It calculates the average value of column2
from table2
for each row processed in table1
based on the matching foreign_key
values. The subquery result is then used as a condition in the WHERE
clause of the outer query.
Let’s write down a correlated query and test the output below:
#!/usr/bin/env bash mkdir -p /var/run/mysqld chmod 777 -R /var/run/mysqld chown -R mysql:mysql /var/lib/mysql /var/run/mysqld # check if mysql is running before restarting it /usr/bin/mysqld_safe & # wait for mysql to start up echo "Please wait for 3 seconds ..." sleep 3 mysql -u root -Bse "DROP DATABASE IF EXISTS MovieIndustry;" clear # Launch MySQL mysql < mysql.sql
Line 2: Use the database mysql
to create tables.
Lines 5–16: We have two tables, table1
and table2
. table1
has columns id
and column1
, while table2
has columns id
, column2
, and foreign_key
referencing table1’s id
column.
Lines 19-28: We insert sample data in both tables.
Lines 31-33: The correlated query selects the column1
values from table1
where the value of column1
is less than the average value of column2
from table2
for each corresponding foreign_key
. This should return some results based on the sample data provided.
Free Resources