Subquery Expressions

A subquery allows you to nest one query within another, enabling more complex data query and analysis.

Subquery Expressions

Example

Create the course table and insert data into the table.

1
2
3
4
5
CREATE TABLE course(cid VARCHAR(10) COMMENT 'No.course',cname VARCHAR(10) COMMENT 'course name',teid VARCHAR(10) COMMENT 'No.teacher');

INSERT INTO course VALUES('01' , 'course1' , '02'); 
INSERT INTO course VALUES('02' , 'course2' , '01'); 
INSERT INTO course VALUES('03' , 'course3' , '03');

Create the teacher table and insert data into the table.

1
2
3
4
5
6
CREATE TABLE teacher(teid VARCHAR(10) COMMENT 'Teacher ID',tname VARCHAR(10) COMMENT'Teacher name');

INSERT INTO teacher VALUES('01' , 'teacher1'); 
INSERT INTO teacher VALUES('02' , 'teacher2');
INSERT INTO teacher VALUES('03' , 'teacher3');
INSERT INTO teacher VALUES('04' , 'teacher4');

Query the teacher records in the course table.

1
SELECT * FROM teacher WHERE EXISTS (SELECT * FROM course WHERE course.teid = teacher.teid);

Query the teacher records that are not in the course table.

1
SELECT * FROM teacher WHERE NOT EXISTS (SELECT * FROM course WHERE course.teid = teacher.teid);

Query the course table for teacher information based on the teacher ID.

1
SELECT * FROM course WHERE teid IN (SELECT teid FROM teacher );

Query the information about teachers who are not in the course table.

1
SELECT * FROM teacher WHERE teid NOT IN (SELECT teid FROM course );

Compare the main query fields on the left with the subquery fields on the right to obtain the required result set.

1
SELECT * FROM course WHERE teid < ANY (SELECT teid FROM teacher where teid<>'04');

or

1
SELECT * FROM course WHERE teid < some (SELECT teid FROM teacher where teid<>'04');

The value in the teid column must be smaller than the minimum value in the set to be true.

1
SELECT * FROM course WHERE teid < ALL(SELECT teid FROM teacher WHERE teid<>'01');

Important Notes

A subquery can be nested in the SELECT statement to implement a more complex query. A subquery can also use the results of other queries in the WHERE clause to better filter data. However, subqueries may cause query performance problems and make code difficult to read and understand. Therefore, when using SQL subqueries in databases such as GaussDB, use them based on the site requirements.