You are on page 1of 2

EXISTS AND NOT EXISTS COMMANDS

1.
2. CREATE TABLE customer(  
3.   cust_id int NOT NULL,  
4.   name varchar(35),  
5.   occupation varchar(25),  
6.   age int  
7. );  

1. CREATE TABLE orders (  
2.     order_id int NOT NULL,   
3.     cust_id int,   
4.     prod_name varchar(45),  
5.     order_date date  
6. );  
Next, we need to insert values into both tables. Execute the below statements:

1. INSERT INTO customer(cust_id, name, occupation, age)   
2. VALUES (101, 'Peter', 'Engineer', 32),  
3. (102, 'Joseph', 'Developer', 30),  
4. (103, 'John', 'Leader', 28),  
5. (104, 'Stephen', 'Scientist', 45),  
6. (105, 'Suzi', 'Carpenter', 26),  
7. (106, 'Bob', 'Actor', 25),  
8. (107, NULL, NULL, NULL);  

1. INSERT INTO orders (order_id, cust_id, prod_name, order_date)   
2. VALUES (1, '101', 'Laptop', '2020-01-10'),  
3. (2, '103', 'Desktop', '2020-02-12'),  
4. (3, '106', 'Iphone', '2020-02-15'),  
5. (4, '104', 'Mobile', '2020-03-05'),  
6. (5, '102', 'TV', '2020-03-20');  
To verify the tables, run the SELECT command as below:

1. msql> SELECT * FROM customer;  
2. AND,  
3. mysql> SELECT * FROM orders;  

MySQL SELECT EXISTS Example


In this example, we are going to use EXISTS operator to find the name and occupation of the
customer who has placed at least one order:

1. mysql> SELECT name, occupation FROM customer  
2. WHERE EXISTS (SELECT * FROM Orders   
3. WHERE customer.cust_id = Orders.cust_id);  
if we want to get the name of the customer who has not placed an order, then use the NOT
EXISTS operator:

1. mysql> SELECT name, occupation FROM customer  
2. WHERE NOT EXISTS (SELECT * FROM Orders   
3. WHERE customer.cust_id = Orders.cust_id);  

ANY COMMAND
1. CREATE TABLE table1 (  
2.     num_value INT  
3. );   
4. INSERT INTO table1 (num_value)   
5. VALUES(10), (20), (25);  
6.   
7. CREATE TABLE table2 (  
8.     num_val int  
9. );   
10. INSERT INTO table2 (num_val)  
11. VALUES(20), (7), (10);  

1. SELECT num_value FROM table1   
2. WHERE num_value > ANY (SELECT num_val FROM table2);  

You might also like