Esta página ainda não está disponível no idioma selecionado. Estamos trabalhando para adicionar mais opções de idiomas. Agradecemos sua compreensão.

Compute
Elastic Cloud Server
Huawei Cloud Flexus
Bare Metal Server
Auto Scaling
Image Management Service
Dedicated Host
FunctionGraph
Cloud Phone Host
Huawei Cloud EulerOS
Networking
Virtual Private Cloud
Elastic IP
Elastic Load Balance
NAT Gateway
Direct Connect
Virtual Private Network
VPC Endpoint
Cloud Connect
Enterprise Router
Enterprise Switch
Global Accelerator
Management & Governance
Cloud Eye
Identity and Access Management
Cloud Trace Service
Resource Formation Service
Tag Management Service
Log Tank Service
Config
OneAccess
Resource Access Manager
Simple Message Notification
Application Performance Management
Application Operations Management
Organizations
Optimization Advisor
IAM Identity Center
Cloud Operations Center
Resource Governance Center
Migration
Server Migration Service
Object Storage Migration Service
Cloud Data Migration
Migration Center
Cloud Ecosystem
KooGallery
Partner Center
User Support
My Account
Billing Center
Cost Center
Resource Center
Enterprise Management
Service Tickets
HUAWEI CLOUD (International) FAQs
ICP Filing
Support Plans
My Credentials
Customer Operation Capabilities
Partner Support Plans
Professional Services
Analytics
MapReduce Service
Data Lake Insight
CloudTable Service
Cloud Search Service
Data Lake Visualization
Data Ingestion Service
GaussDB(DWS)
DataArts Studio
Data Lake Factory
DataArts Lake Formation
IoT
IoT Device Access
Others
Product Pricing Details
System Permissions
Console Quick Start
Common FAQs
Instructions for Associating with a HUAWEI CLOUD Partner
Message Center
Security & Compliance
Security Technologies and Applications
Web Application Firewall
Host Security Service
Cloud Firewall
SecMaster
Anti-DDoS Service
Data Encryption Workshop
Database Security Service
Cloud Bastion Host
Data Security Center
Cloud Certificate Manager
Edge Security
Managed Threat Detection
Blockchain
Blockchain Service
Web3 Node Engine Service
Media Services
Media Processing Center
Video On Demand
Live
SparkRTC
MetaStudio
Storage
Object Storage Service
Elastic Volume Service
Cloud Backup and Recovery
Storage Disaster Recovery Service
Scalable File Service Turbo
Scalable File Service
Volume Backup Service
Cloud Server Backup Service
Data Express Service
Dedicated Distributed Storage Service
Containers
Cloud Container Engine
SoftWare Repository for Container
Application Service Mesh
Ubiquitous Cloud Native Service
Cloud Container Instance
Databases
Relational Database Service
Document Database Service
Data Admin Service
Data Replication Service
GeminiDB
GaussDB
Distributed Database Middleware
Database and Application Migration UGO
TaurusDB
Middleware
Distributed Cache Service
API Gateway
Distributed Message Service for Kafka
Distributed Message Service for RabbitMQ
Distributed Message Service for RocketMQ
Cloud Service Engine
Multi-Site High Availability Service
EventGrid
Dedicated Cloud
Dedicated Computing Cluster
Business Applications
Workspace
ROMA Connect
Message & SMS
Domain Name Service
Edge Data Center Management
Meeting
AI
Face Recognition Service
Graph Engine Service
Content Moderation
Image Recognition
Optical Character Recognition
ModelArts
ImageSearch
Conversational Bot Service
Speech Interaction Service
Huawei HiLens
Video Intelligent Analysis Service
Developer Tools
SDK Developer Guide
API Request Signing Guide
Terraform
Koo Command Line Interface
Content Delivery & Edge Computing
Content Delivery Network
Intelligent EdgeFabric
CloudPond
Intelligent EdgeCloud
Solutions
SAP Cloud
High Performance Computing
Developer Services
ServiceStage
CodeArts
CodeArts PerfTest
CodeArts Req
CodeArts Pipeline
CodeArts Build
CodeArts Deploy
CodeArts Artifact
CodeArts TestPlan
CodeArts Check
CodeArts Repo
Cloud Application Engine
MacroVerse aPaaS
KooMessage
KooPhone
KooDrive

GaussDB(DWS) Subquery Expressions

Updated on 2024-12-18 GMT+08:00

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

Subquery Expressions

  • EXISTS/NOT EXISTS

    Before the main query runs, the subquery runs and its result determines if the main query continues. EXISTS returns true if the subquery returns at least one row. NOT EXISTS returns true if the subquery returns no rows.

    Syntax:

    1
    WHERE column_name EXISTS/NOT EXISTS (subquery)
    
  • IN/NOT IN

    IN and NOT IN are operators that check if a value is in a set of values. IN returns true when the outer query row matches a subquery row. NOT IN returns true when the outer query row does not match any subquery row.

    Syntax:

    1
    WHERE column_name IN/NOT IN (subquery)
    
  • ANY/SOME

    ANY indicates that any value in a subquery can match a value in an outer query. SOME is the same as ANY, but the syntax is different.

    The subquery can return only one column. The expression on the left uses operators (=, <>, <, <=, >, >=) to compare the value with each subquery row. The result must be a Boolean value. The result of ANY is true if any true result is obtained. The result is false if no true result is found (including the case where the subquery returns no rows).

    Syntax:

    1
    WHERE column_name operator ANY/SOME (subquery)
    
  • ALL

    The subquery on the right must return only one field. The expression on the left uses operators (=, <>, <, <=, >, >=) to compare the value with each subquery row. The result must be a Boolean value. The result of ALL is true if all rows yield true (including the case where the subquery returns no rows). The result is false if any false result is found.

    Syntax:

    1
    WHERE column_name operator ALL (subquery)
    
    Table 1 ALL conditions

    Condition

    Description

    column_name > ALL(...)

    The column_name value must be greater than the maximum value of a set to be true.

    column_name >= ALL(...)

    The column_name value must be greater than or equal to the maximum value of a set to be true.

    column_name < ALL(...)

    The column_name value must be smaller than the minimum value of a set to be true.

    column_name <= ALL(...)

    The column_name value must be smaller than or equal to the minimum value of a set to be true.

    column_name <> ALL(...)

    The column_name value cannot be equal to any value in a set to be true.

    column_name = ALL(...)

    The column_name value must be equal to any value in a set to be true.

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');
  • EXISTS/NOT EXISTS example

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);

  • IN/NOT IN example

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 );

  • ANY/SOME example

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');

  • ALL example

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

  • Duplicate subquery statements are not allowed in an SQL statement.
  • Avoid scalar sub-queries whenever possible. A scalar subquery is a subquery whose result is one value and whose condition expression uses an equal operator.
  • Do not use subqueries in the SELECT target columns. Otherwise, the plan cannot be pushed down, affecting the execution performance.
  • It is recommended that the nested subqueries cannot exceed two layers. Subqueries cause temporary table overhead. Therefore, complex queries must be optimized based on service logic.

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.

Usamos cookies para aprimorar nosso site e sua experiência. Ao continuar a navegar em nosso site, você aceita nossa política de cookies. Saiba mais

Feedback

Feedback

Feedback

0/500

Selected Content

Submit selected content with the feedback