![]() |
In SQL, for matching multiple values in the same column, we need to use some special words in our query. Below, 3 methods are demonstrated to achieve this using the IN, LIKE and comparison operator(>=). For this article, we will be using the Microsoft SQL Server as our database. Step 1: Create a Database. For this use the below command to create a database named GeeksForGeeks. Query: CREATE DATABASE GeeksForGeeks Output: Step 2: Use the GeeksForGeeks database. For this use the below command. Query: USE GeeksForGeeks Output: Step 3: Create a table CARS inside the database GeeksForGeeks. This table has 3 columns namely CAR_NAME, COMPANY and COST containing the name, company and cost of various cars. Query: CREATE TABLE CARS( CAR_NAME VARCHAR(10), COMPANY VARCHAR(10), COST INT); Output: Step 4: Describe the structure of the table CARS. Query: EXEC SP_COLUMNS CARS; Output: Step 5: Insert 5 rows into the CARS table. Query: INSERT INTO CARS VALUES('INNOVA','TOYOTA',10000); INSERT INTO CARS VALUES('CAMRY','TOYOTA',20000); INSERT INTO CARS VALUES('CIAZ','HONDA',30000); INSERT INTO CARS VALUES('POLO','VOLKSWAGEN',50000); INSERT INTO CARS VALUES('BENZ','MERCEDES',100000); Output: Step 6: Display all the rows of the CARS table. Query: SELECT * FROM CARS; Output: Step 7: Retrieve the details of all the cars belonging to the companies TOYOTA and HONDA. Note – Use of IN for matching multiple values i.e. TOYOTA and HONDA in the same column i.e. COMPANY. Syntax: SELECT * FROM TABLE_NAME WHERE COLUMN_NAME IN (MATCHING_VALUE1,MATCHING_VALUE2); Query: SELECT * FROM CARS WHERE COMPANY IN ('TOYOTA','HONDA'); Output: Step 8: Retrieve the details of all the cars whose name starts with the letter C. Note – Use of LIKE for matching multiple values i.e. CAMRY and CIAZ in the same column i.e. CAR_NAME. Syntax: SELECT * FROM TABLE_NAME WHERE COLUMN_NAME LIKE 'STARTING_LETTER%'; Query: SELECT * FROM CARS WHERE CAR_NAME LIKE 'C%'; Output: Step 9: Retrieve the details of all the cars having cost greater than or equal to 30000. Note – Use of comparison operator >= for matching multiple values i.e. 30000, 50000 and 100000 in the same column i.e. COST. Syntax: SELECT * FROM TABLE_NAME WHERE COLUMN_NAME >=VALUE; Query: SELECT * FROM CARS WHERE COST>=30000; Output: |
Reffered: https://www.geeksforgeeks.org
SQL |
Type: | Geek |
Category: | Coding |
Sub Category: | Tutorial |
Uploaded by: | Admin |
Views: | 13 |