SQL Queries ALL Updated
SQL Queries ALL Updated
SQL TABLES;
CREATE TABLE table_name(
column1 datatype,
column2 datatype,
column3 datatype,
.....
columnN datatype,
PRIMARY KEY( one or more columns )
);
INSERT INTO students (id, first_name, last_name, age, gender, email, address,
phone_number)
VALUES
(1, 'John', 'Doe', 20, 'Male', '[email protected]', '123 Main St', '123-456-7890'),
(2, 'Jane', 'Smith', 22, 'Female', '[email protected]', '456 Elm St', '987-654-3210'),
(3, 'Michael', 'Johnson', 19, 'Male', '[email protected]', '789 Oak St', '555-123-
4567'),
(4, 'Emily', 'Williams', 21, 'Female', '[email protected]', '321 Maple Ave', '111-
222-3333'),
(5, 'Daniel', 'Brown', 20, 'Male', '[email protected]', '444 Pine St', '444-555-
6666'),
(6, 'Olivia', 'Jones', 23, 'Female', '[email protected]', '567 Cedar Ave', '777-888-
9999'),
(7, 'William', 'Taylor', 20, 'Male', '[email protected]', '890 Walnut St', '222-333-
4444'),
(8, 'Sophia', 'Anderson', 21, 'Female', '[email protected]', '123 Oakwood Ave',
'888-999-0000'),
(9, 'Matthew', 'Thomas', 22, 'Male', '[email protected]', '456 Maplewood Dr',
'555-777-8888'),
(10, 'Ava', 'Jackson', 20, 'Female', '[email protected]', '789 Pinecrest Rd', '777-000-
1111'),
(11, 'Jacob', 'White', 23, 'Male', '[email protected]', '321 Elmwood Ln', '444-222-
3333'),
(12, 'Mia', 'Harris', 21, 'Female', '[email protected]', '654 Pinehill Ave', '666-777-
8888'),
(13, 'Ethan', 'Martin', 20, 'Male', '[email protected]', '987 Cedarwood Rd', '111-
222-3333'),
(14, 'Charlotte', 'Thompson', 22, 'Female', '[email protected]', '753 Oakhill
Dr', '888-999-1111'),
(15, 'Alexander', 'Garcia', 19, 'Male', '[email protected]', '369 Maple Ave',
'333-444-5555'),
(16, 'Amelia', 'Davis', 21, 'Female', '[email protected]', '852 Willow St', '555-666-
7777'),
(17, 'James', 'Rodriguez', 20, 'Male', '[email protected]', '147 Elmwood Ave',
'777-888-9999'),
(18, 'Lily', 'Lopez', 22, 'Female', '[email protected]', '963 Pine St', '222-333-4444'),
(19, 'Benjamin', 'Wilson', 23, 'Male', '[email protected]', '258 Oakwood Ln',
'666-777-8888'),
(20, 'Grace', 'Lee', 20, 'Female', '[email protected]', '753 Maple Ave', '111-222-3333'),
(21, 'Daniel', 'Hall', 22, 'Male', '[email protected]', '369 Cedarwood Dr', '444-555-
6666'),
(22, 'Victoria', 'Young', 21, 'Female', '[email protected]', '852 Elm St', '777-888-
9999'),
(23, 'Henry', 'Gonzalez', 20, 'Male', '[email protected]', '456 Pinecrest Ave',
'222-333-4444'),
(24, 'Sofia', 'Clark', 23, 'Female', '[email protected]', '963 Oakwood Rd', '555-666-
7777'),
(25, 'Christopher', 'Lewis', 21, 'Male', '[email protected]', '147 Maplewood
Ave', '888-999-1111');
Example
The following SQL command will create the CUSTOMERS table only when there
is no table exists with the same name otherwise it will exit without any error.
CREATE TABLE IF NOT EXISTS CUSTOMERS(
Emp_ID INT NOT NULL,
NAME VARCHAR (20) NOT NULL,
Emp_AGE INT NOT NULL,
ADDRESS CHAR (25),
PRIMARY KEY (ID)
);
Creating a Table from an Existing Table
Instead of creating a new table every time, one can also copy an existing table and
its contents including its structure, into a new table. This can be done using a
combination of the CREATE TABLE statement and the SELECT statement. Since
its structure is copied, the new table will have the same column definitions as the
original table. Furthermore, the new table would be populated using the existing
values from the old table.
Syntax
The basic syntax for creating a table from another table is as follows −
FROM EXISTING_TABLE_NAME
[WHERE CONDITION];
Here, column1, column2... are the fields of the existing table and the same would
be used to create fields of the new table.
Example
FROM CUSTOMERS;
FROM students;
The AS keyword is used to specify the name of the new table ( Information).
But if you do not specify the WHERE condition it will remove all the rows from the table.
There are some more terms similar to DELETE statement like as DROP statement and
TRUNCATE statement, but they are not exactly same there are some differences between
them.
Verification
Now, the CUSTOMERS table is truncated and the output from SELECT statement
will be as shown in the code block below −
TRUNCATE vs DELETE
Even though the TRUNCATE and DELETE commands work similar logically,
there are some major differences that exist between them. They are detailed in the
table below.
DELETE TRUNCATE
The DELETE command in SQL removes one or SQL's TRUNCATE command is used to
more rows from a table based on the conditions remove all of the rows from a table, regardless
specified in a WHERE Clause. of whether or not any conditions are met.
It makes a record of each and every transaction The only activity recorded is the deallocation
in the log file. of the pages on which the data is stored.
TRUNCATE vs DROP
Unlike TRUNCATE that resets the table structure, DROP command completely
frees the tablespace from the memory. They are both Data Definition Language
(DDL) operations as they interact with the definitions of database objects; which
allows the database to automatically commit once these commands are executed
with no chance to roll back.
However, there are still some differences exist between these two commands,
which have been summarized in the following table −
DROP TRUNCATE
All the integrity constraints are removed. The integrity constraints still exist in the table.
DROP command is much slower than TRUNCATE command is faster than both DROP
TRUNCATE but faster than DELETE. and DELETE commands.
SQL - Clone Tables
There may be a situation when you need an exact copy of a table with the same
columns, attributes, indexes, default values and so forth. Instead of spending time
on creating the exact same version of an existing table, you can create a clone of
the existing table.
SQL Cloning Operation allows to create the exact copy of an existing table along
with its definition. There are three types of cloning possible using SQL in various
RDBMS; they are listed below −
Simple Cloning
Shallow Cloning
Deep Cloning
To break this process down, a new table is created using the CREATE TABLE
statement; and the data from the existing table, as a result of SELECT statement, is
copied into the new table.
Here, clone table inherits only the basic column definitions like the NULL settings
and default values from the original table. It does not inherit the indices and
AUTO_INCREMENT definitions.
Syntax
Example
Consider the following existing CUSTOMERS table which will be cloned in next
new few steps.
Now let's use the following SQL statement to create NEW_CUSTOMERS table
using the existing table CUSTOMERS.
Output
Verification
To verify whether the table has been cloned successfully, we can use the following
SELECT query −
Here, the clone table contains only the structure of the original table along with the
column attributes including indices and AUTO_INCREMENT definition.
Syntax
Example
Output
To verify whether the table has been cloned successfully, we can use the following
DESC table_name query −
DESC SHALL_CUSTOMERS;
This will display the following information about the SHALL_CUSTOMERS table
which is just a replica of CUSTOMERS table −
Since it is a combination of shallow and simple cloning, this type of cloning will
have two different queries to be executed: one with CREATE TABLE statement
and one with INSERT INTO statement. The CREATE TABLE statement will
create the new table by including all the attributes of existing table; and INSERT
INTO statement will insert the data from existing table into new table.
Syntax
Example
Now second step is to copy all the records from the CUSTOMERS table to
DEEP_CUSTOMERS.
Output
To verify whether the table has been cloned successfully, we can use the following
SELECT query −
Various RDBMS, like MySQL, support temporary tables starting from version
3.23 onwards. If you are using an older version of MySQL than 3.23, you can't use
temporary tables, but you can use heap tables.
As stated earlier, temporary tables will only last as long as the client session is
alive. If you run the code in a PHP script, the temporary table will be destroyed
automatically when the script finishes executing. If you are connected to the
MySQL database server through a MySQL client program, then the temporary
table will exist until you close the client connection or manually destroy the table.
column1 datatype,
column2 datatype,
column3 datatype,
.....
columnN datatype,
);
Example
);
Just like normal tables you can insert data into a temporary table using the
INSERT statement. Following query inserts 3 records into the above created
temporary table −
The temporary table CUSTOMERS will be created and will have following
records −
ID NAME AGE ADDRESS SALARY
When you issue a SHOW TABLES command, then your temporary table will not
be displayed in the list of tables. To verify whether the temporary table is created
you need to retrieve its data using the SELECT statement. Since all the temporary
tables will be removed when the current session is closed, if you log out of the
MySQL session and then issue a SELECT command, you will not find temporary
table in the database.
Example
Following query drops the temporary table CUSTOMERS created in the previous
example –
DROP TEMPORARY TABLE CUSTOMERS;
Verification
Since we have removed the temporary table CUSTOMERS, if you try to retrieve
the contents of it using the SELECT statement, it will generate an error saying the
table does not exist.
The ALTER TABLE command can also change characteristics of a table such as
the storage engine used for the table. We will make use of the following table in
our examples.
Syntax
(0 rows affected)
Verification
Following is the example to DROP sex column from the existing table.
(0 rows affected)
Verification
Now, the CUSTOMERS table is changed and following would be the output from
the SELECT statement.
Suppose you have a table named students with the following structure:
+----+------------+------------+
| id | first_name | birthdate |
+----+------------+------------+
| 1 | John | 2000-01-15 |
| 2 | Jane | 1999-05-23 |
| 3 | Mark | 2001-03-10 |
+----+------------+------------+
Let's say you want to change the data type of the birthdate column from DATE to
VARCHAR(10) to store dates as strings in the format 'YYYY-MM-DD':
After running this SQL statement, the birthdate column's data type will be
changed, and the table will look like this:
+----+------------+------------+
| id | first_name | birthdate |
+----+------------+------------+
| 1 | John | 2000-01-15 |
| 2 | Jane | 1999-05-23 |
| 3 | Mark | 2001-03-10 |
+----+------------+------------+
In this example:
We use the MODIFY COLUMN clause to modify the properties of the birthdate
column.
We change the data type from DATE to VARCHAR(10) to store dates as strings in
the 'YYYY-MM-DD' format.
ID INT,
Suppose you have a table called employees with the following structure:
+----+-----------+-----------+--------+
+----+-----------+-----------+--------+
+----+-----------+-----------+--------+
Now, let's say you frequently run queries to find employees by their last name.
Without an index on the last_name column, MySQL would have to scan the entire
table row by row to find matching employees. This process can be slow and
inefficient, especially for large datasets.
To improve the performance of such queries, you can create an index on the
last_name column using the ALTER TABLE statement:
After creating this index, queries that search for employees by last name will be
significantly faster because MySQL can use the index to quickly locate the relevant
rows. For example:
With the index in place, MySQL can use it to quickly identify the rows that
match the condition, resulting in faster query execution.
Example
Output
The output will be displayed as −
Query OK, 0 rows affected (0.003 sec)
Records: 0 Duplicates: 0 Warnings: 0
Example
Before we add a primary key to an existing table, first let's create a new table
called EMPLOYEES as follows:
);
To verify the above query if you describe the table using the DESC EMPLOYEES
command −
DESC EMPLOYEES;
This will display the structure of the table created: column names, their respective
data types, constraints (if any) etc.
In MySQL, you can use the ALTER TABLE statement with the ADD
CONSTRAINT clause to add various types of constraints to an existing
table. Constraints are rules that define the acceptable data values that
can be stored in a table. They help ensure data integrity and
consistency in the database. MySQL supports several types of
constraints, including primary keys, foreign keys, unique constraints,
and check constraints.
table_name: Replace this with the name of the table to which you
want to add a constraint.
constraint_name: Specify a unique name for the constraint.
constraint_type: Choose the type of constraint you want to add
(e.g., PRIMARY KEY, FOREIGN KEY, UNIQUE, CHECK).
column_name: Specify the column(s) to which the constraint
applies.
These examples illustrate how to add various types of constraints to a table using the ALTER
TABLE statement. Constraints play a vital role in maintaining data integrity and enforcing
data rules in a database.
SQL - Constraints
Table of Content
SQL Constraints Introduction
SQL Create Constraints
NOT NULL Constraint
UNIQUE Key Constraint
DEFAULT Value Constraint
PRIMARY Key Constraint
FOREIGN Key Constraint
CHECK Value Constraint
INDEX Constraint
Dropping SQL Constraints
Data Integrity Constraints
SQL Constraints
SQL Constraints are the rules applied to a data columns or the complete table to
limit the type of data that can go into a table. When you try to perform any
INSERT, UPDATE, or DELETE operation on the table, RDBMS will check
whether that data violates any existing constraints and if there is any violation
between the defined constraint and the data action, it aborts the operation and
returns an error.
We can define a column level or a table level constraints. The column level
constraints are applied only to one column, whereas the table level constraints are
applied to the whole table.
.
CREATE TABLE table_name (
column1 datatype constraint,
column2 datatype constraint,
column3 datatype constraint,
....
);
Different RDBMS allows to define different constraints. This tutorial will discuss
about 7 most important constraints available in MySQL.
SELECT DISTINCT
TC.CONSTRAINT_NAME,
KCU.COLUMN_NAME,
TC.CONSTRAINT_TYPE
FROM
INFORMATION_SCHEMA.TABLE_CONSTRAINTS TC
JOIN
INFORMATION_SCHEMA.KEY_COLUMN_USAGE KCU
ON
TC.CONSTRAINT_NAME = KCU.CONSTRAINT_NAME
WHERE
KCU.TABLE_NAME = 'customers2'
AND TC.CONSTRAINT_SCHEMA = 'student';
SELECT CONSTRAINT_NAME
FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS
WHERE TABLE_NAME = 'CUSTOMERS11'
AND CONSTRAINT_TYPE = 'UNIQUE';
);
AuthorID INT,
INSERT INTO Authors (AuthorID, Name) VALUES (2, 'George R.R. Martin');
INSERT INTO Books (BookID, Title, AuthorID) VALUES (1, 'Harry Potter', 1);
INSERT INTO Books (BookID, Title, AuthorID) VALUES (2, 'Game of Thrones',
2);
FROM Books
JOIN Authors ON Books.AuthorID = Authors.AuthorID;
SELECT
CONSTRAINT_NAME
FROM
INFORMATION_SCHEMA.KEY_COLUMN_USAGE
WHERE
TABLE_NAME = 'Books'
INDEX Constraint
The INDEX constraints are created to speed up the data retrieval from the
database. An Index can be created by using a single or group of columns in a table.
A table can have a single PRIMARY Key but can have multiple INDEXES. An
Index can be Unique or Non Unique based on requirements. Following is an
example to create an Index on Age Column of the CUSTOMERS table.
Here, column1, column2... are the fields of a table whose values you want to fetch.
If you want to fetch all the columns available in a table, then you can use the
following syntax −
Now, insert values into this table using the INSERT statement as follows −
The following statement fetches the ID, Name and Salary fields of the records
available in CUSTOMERS table.
ID NAME Salary
1 Ramesh 2000.00
2 Khilan 1500.00
3 kaushik 2000.00
4 Chaitali 6500.00
5 Hardik 8500.00
6 Komal 4500.00
7 Muffy 10000.00
SELECT mathematical_expression;
Example
Following is an example which multiply two given numbers using SQL statement.
SELECT 56*65;
The query above produces the following output −
56*65
3640
DETAILS ADDRESS
Chaitali 25 Mumbai
Hardik 27 Bhopal
kaushik 23 Kota
Khilan 25 Delhi
Komal 22 Hyderabad
Muffy 24 Indore
Ramesh 32 Ahmedabad
However, it's important to note that the SELECT INTO statement does not
preserve any indexes, constraints, or other properties of the original table, and the
new table will not have any primary keys or foreign keys defined by default.
Therefore, you may need to add these properties to the new table manually if
necessary.
MySQL doesn't support the SELECT ... INTO TABLE Sybase SQL extension i.e.
in MySQL you cannot use the SELECT ... INTO statement to insert data from
one table to another. Instead of this, we can use INSERT INTO ...
SELECT statement or, CREATE TABLE ... SELECT.
Syntax
Following is the basic syntax of the SQL SELECT INTO statement in SQL Server
−
Let us create the CUSTOMERS table which contains the personal details of
customers including their name, age, address and salary etc. as shown below −
Now, insert values into this table using the INSERT statement as follows −
We get the following result. We can observe that 7 rows have been modified.
(7 rows affected)
Verification
We can verify whether the changes are reflected in a table by retrieving its contents
using the SELECT statement. Following is the query to display the records in the
CUSTOMER_BACKUP table −
Syntax
We get the following result. We can observe that 7 rows have been modified.
(7 rows affected)
Verification
We can verify whether the changes are reflected in a table by retrieving its contents
using the SELECT statement. Following is the query to display the records in the
CUSTOMER_DETAILS table −
Ramesh 32 Ahmedabad
Khilan 25 Delhi
Kaushik 23 Kota
Chaitali 25 Mumbai
Hardik 27 Bhopal
Komal 22 Hyderabad
Muffy 24 Indore
Note: The new table will not include any other columns from the original table.
Also the original table remains unchanged.
SQL - Insert Into... Select Statement
When these statements are used together, the SELECT statement first retrieves the
data from an existing table and the INSERT INTO statement inserts the retrieved
data into another table (if they have same table structures).
Syntax
In the database where we are going to insert data, source and target tables
already exist.
The structure of the source and target tables are same.
Example
Assume we have created a table named CUSTOMERS which contains the
personal details of customers including their name, age, address and salary etc.., as
shown below −
CREATE TABLE CUSTOMERS (
ID INT NOT NULL,
NAME VARCHAR (20) NOT NULL,
AGE INT NOT NULL,
ADDRESS CHAR (25),
SALARY DECIMAL (18, 2),
PRIMARY KEY (ID)
);
Now, insert values into this table using the INSERT statement as follows −
Create another table named BUYERS with same structure as the CUSTOMERS
table.
CREATE TABLE BUYERS (
ID INT NOT NULL,
NAME VARCHAR (20) NOT NULL,
AGE INT NOT NULL,
ADDRESS CHAR (25),
SALARY DECIMAL (18, 2),
PRIMARY KEY (ID)
);
Following query copies all the records from the CUSTOMERS table
to BUYERS −
INSERT INTO BUYERS SELECT * FROM CUSTOMERS;
Verification
If you verify the contents of the BUYERS table using the SELECT statement as −
Example
Let us create a table named NAMESTARTSWITH_K with the same structure as
the CUSTOMER table using the CREATE statement as −
CREATE TABLE NAMESTARTSWITH_K (
ID INT NOT NULL,
NAME VARCHAR (20) NOT NULL,
AGE INT NOT NULL,
ADDRESS CHAR (25),
SALARY DECIMAL (18, 2),
PRIMARY KEY (ID)
);
Following query, inserts the records of the customers whose name starts with the
letter k from the CUSTOMERS table to the BUYERS table −
INSERT INTO NAMESTARTSWITH_K
SELECT * FROM CUSTOMERS
WHERE NAME LIKE 'k%';
Verification
Following is the SELECT statement to verify the contents of the above created
table −
Example
But, before proceeding further, let us truncate all rows in the BUYERS table using
the following statement −
Following query inserts the top 3 records from the CUSTOMERS table to the
BUYERS table −
INSERT INTO BUYERS SELECT * FROM CUSTOMERS ORDER BY ID ASC
LIMIT 3;
Verification
To filter records that needs to be modified, you can use a WHERE clause with
UPDATE statement. Using a WHERE clause, you can either update a single row
or multiple rows.
Since it only interacts with the data of a table, the SQL UPDATE statement needs
to used cautiously. If the rows to be modified aren't selected properly, all the rows
in the table will be affected and the correct table data is either lost or needs to be
reinserted.
The SQL UPDATE statement makes use of locks on each row while modifying
them in a table, and once the row is modified, the lock is released. Therefore, it can
either make changes to a single row or multiple rows with a single query.
Syntax
The basic syntax of the SQL UPDATE statement with a WHERE clause is as
follows −
UPDATE table_name
SET column1 = value1, column2 = value2...., columnN = valueN
WHERE [condition];
You can combine N number of conditions using the AND or the OR operators.
Example
Assume we have created a table named CUSTOMERS using the CREATE
TABLE statement as shown below −
CREATE TABLE CUSTOMERS (
ID INT NOT NULL,
NAME VARCHAR (20) NOT NULL,
AGE INT NOT NULL,
ADDRESS CHAR (25),
SALARY DECIMAL (18, 2),
PRIMARY KEY (ID)
);
Now, insert values into this table using the INSERT statement as follows −
The following query will update the ADDRESS for a customer whose ID number
is 6 in the table.
To verify whether the records of the table are modified or not, use the following
SELECT query below −
However, to update multiple columns, set the new values to all the columns that
need to be updated. In this case, using the WHERE clause would narrow down the
records of the table and not using the clause would change all the values in these
columns.
Syntax
UPDATE table_name
SET column_name1 = new_value, column_name2 = new_value...
WHERE condition(s)
Example
If you want to modify all the AGE and the SALARY column values in the
CUSTOMERS table, you do not need to use the WHERE clause as the UPDATE
query would be enough. Following query increases the age of all the customers by
5 years and adds 3000 to all the salary values −
To verify whether the records of the table are modified or not, use the following
SELECT query below −
Example
But, if you want to modify the ADDRESS and the SALARY columns of selected
records in the CUSTOMERS table, you need to specify a condition to filter the
records to be modified, using the WHERE clause, as shown in the following query
−
To verify whether the records of the table are modified or not, use the following
SELECT query below −
The SQL ORDER BY clause is used to sort the data in ascending or descending
order, based on one or more columns. By default, some databases sort the query
results in an ascending order.
In addition to that, ORDER BY clause can also sort the data in a database table in a
preferred order. This case may not sort the records of a table in any standard order
(like alphabetical or lexicographical), but, they could be sorted based on any
external condition. For instance, in an ORDERS table containing the list of orders
made by various customers of an organization, the details of orders placed can be
sorted based on the dates on which those orders are made. This need not be
alphabetically sorted, instead, it is based on "first come first serve".
Syntax
The basic syntax of the ORDER BY clause which would be used to sort the result
in an ascending or descending order is as follows −
SELECT column-list
FROM table_name
[WHERE condition]
[ORDER BY column1, column2, .. columnN] [ASC | DESC];
You can use more than one column in the ORDER BY clause. Make sure that
whatever column you are using to sort, that column should be in the column-list.
Example
Assume we have created a table named CUSTOMERS using the CREATE
TABLE statement as shown below −
CREATE TABLE CUSTOMERS (
ID INT NOT NULL,
NAME VARCHAR (20) NOT NULL,
AGE INT NOT NULL,
ADDRESS CHAR (25),
SALARY DECIMAL (18, 2),
PRIMARY KEY (ID)
);
Now, insert values into this table using the INSERT statement as follows −
Example
The following query sorts the records of the CUSTOMERS tables in descending
order based on the column NAME.
SELECT * FROM CUSTOMERS ORDER BY NAME DESC;
Output
Example
To fetch the rows with their own preferred order, the SELECT query used would
be as follows −
This will sort the customers by ADDRESS in your own order of preference first,
and in a natural order for the remaining addresses. Also, the remaining Addresses
will be sorted in the reverse alphabetical order.
SQL Operators and Clauses
SQL - WHERE Clause
For instance, you can use the WHERE clause to retrieve details of employees of a
department in an organization, or employees earning salary above/below certain
amount, or details of students eligible for scholarships etc. This clause basically
provides the specification of which records to be retrieved and which are to be to
be neglected.
Syntax
You can specify a condition using the comparison or logical operators such as, >,
<, =, LIKE, NOT, etc.
ID NAME SALARY
4 Chaitali 6500.00
5 Hardik 8500.00
6 Komal 4500.00
7 Muffy 10000.00
UPDATE table_name
SET column1 = value1, column2 = value2, ...
WHERE condition;
Example
In the following query, we are incrementing the salary of the customer named
Ramesh by 10000 by using the WHERE clause along with the UPDATE statement
−
We get the following result. We can observe that the age of 2 customers have been
modified −
To verify if the changes are reflected in the table, we can use SELECT statement as
shown in the following query −
Suppose you want to display records with NAME values ‘Khilan’, ‘Hardik’ and
‘Muffy’ from the CUSTOMERS table, you can use the following query −
If you use WHERE with the IN operator, the DML statement will act on the
the list of values (of a column) specified
Whereas, if you use WHERE with the NOT IN operator, the DML operation
is performed on the values (of a column) that are not there in the specified
list.
Hence, if you use WHERE Clause with NOT IN Operator along with the SELECT
statement, the rows that do not match the list of values are retrieved. Following is
the syntax −
WHERE column_name NOT IN (value1, value2, ...);
Example
In this example, we are displaying the records from CUSTOMERS table, where
AGE is NOT equal to ‘25’, ‘23’ and ‘22’.
Following is the query which would display all the records where the name starts
with K and is at least 4 characters in length −
Following is the syntax for using the AND and OR operators in a WHERE clause
−
In the following query, we are retrieving all rows from the CUSTOMERS table
based on some conditions. The parentheses control the order of evaluation so that
the OR operator is applied first, followed by the AND operator −
For instance, if you have a large number of data stored in a database table, and you
only want to perform operations on first N rows, you can use the TOP clause in
your SQL server query.
MySQL database does not support TOP clause instead of this, we can use
the LIMIT clause to select a limited number of records from a MySQL table.
Similarly, Oracle supports the ROWNUM clause to restrict the records of a table.
The TOP clause is similar to the LIMIT clause.
Syntax
To understand it better let us consider the CUSTOMERS table which contains the
personal details of customers including their name, age, address and salary etc. as
shown below −
Now, insert values into this table using the INSERT statement as follows −
INSERT INTO CUSTOMERS VALUES
(1, 'Ramesh', 32, 'Ahmedabad', 2000.00 ),
(2, 'Khilan', 25, 'Delhi', 1500.00 ),
(3, 'Kaushik', 23, 'Kota', 2000.00 ),
(4, 'Chaitali', 25, 'Mumbai', 6500.00 ),
(5, 'Hardik', 27, 'Bhopal', 8500.00 ),
(6, 'Komal', 22, 'Hyderabad', 4500.00 ),
(7, 'Muffy', 24, 'Indore', 10000.00 );
Now, we are using the TOP clause to fetch the top 4 records from the
CUSTOMERS table without specifying any conditional clauses such as WHERE,
ORDER BY, etc. −
Output
Output
Note − By default, the ORDER BY clause sorts the data in ascending order. So, if
we need to sort the data in descending order, we must use the DESC keyword.
Example
The following query selects the first 40% of the records from the CUSTOMERS
table sorted in the ascending order by their SALARY −
Output
We have the total of 7 records in our table. So 40% of 7 is 2.8. Therefore, SQL
server rounds the result to three rows (the next whole number) as shown in the
output below −
Example
Following is the query to show the details of the first two customers whose name
starts with ‘K’ from the CUSTOMERS table −
Output
Example
In the following query, we are using DELETE statement with TOP clause. Here,
we are deleting the top 2 customers whose NAME starts with ‘K’ −
Output
(2 rows affected)
Verification
We can verify whether the changes are reflected in a table by retrieving its contents
using the SELECT statement as shown below −
If you try to restrict the number of records using the TOP clause, all the eligible
columns may not be filtered.
The WITH TIES clause is used to ensure that the records having the same values
(records with "tied" values) are included in the query results.
Example
Consider the above created table CUSTOMERS. If we need to retrieve the top 2
customers sorted by the ascending order of their SALARY values, the query would
be −
SELECT TOP 2 * FROM CUSTOMERS ORDER BY SALARY;
SELECT *
FROM CUSTOMERS
ORDER BY SALARY
LIMIT 2;
But, the first two salary values (in ascending order) in the table are 1500 and 2000
and there is another column in the CUSTOMERS table with salary value 2000
which is not included in the result.
If you want to retrieve all the columns with first two salary values (when arranged
in the ascending order). We need to use the WITH TIES clause as shown below −
SELECT TOP 2 WITH TIES * FROM CUSTOMERS ORDER BY SALARY;
In SQL, LIMIT and OFFSET are used to set the number of records to return and where to start returning
records from a result set, respectively.
In your query, LIMIT 1 means that only one record should be returned from the subquery.
The OFFSET 1 clause means to skip the first record in the result set. So in this case, the subquery is
returning the second lowest salary from the CUSTOMERS table.
The outer query then returns all records from the CUSTOMERS table where the salary is less than or equal
to this second lowest salary, ordered by salary. So essentially, this query is finding all customers whose
salaries are less than or equal to the second lowest salary in the table.
SELECT *
FROM CUSTOMERS
WHERE SALARY <= (
SELECT DISTINCT SALARY
FROM CUSTOMERS
ORDER BY SALARY
LIMIT 1 OFFSET 1
)
ORDER BY SALARY;
Output
FROM CUSTOMERS
FROM customers
WHERE salary < (SELECT MAX(salary) FROM customers);
For third largest salary:
LIMIT 1 OFFSET 2;
SQL - DISTINCT Keyword
We use DISTINCT keyword with the SELECT statement when there is a need to
avoid duplicate values present in any specific columns/tables. When we use
DISTINCT keyword, SELECT statement returns only the unique records available
in the table.
The SQL DISTINCT Keyword can be associated with SELECT statement to fetch
unique records from single or multiple columns/tables.
Syntax
Example
Following query inserts values into this table using the INSERT statement −
First, let us retrieve the SALARY values from the CUSTOMERS table using the
SELECT query −
1500.00
2000.00
2000.00
4500.00
6500.00
8500.00
10000.00
Now, let us use the DISTINCT keyword with the above SELECT query and then
see the result −
SELECT DISTINCT SALARY FROM CUSTOMERS ORDER BY SALARY;
Output
This would produce the following result where we do not have any duplicate entry
−
SALARY
1500.00
2000.00
4500.00
6500.00
8500.00
10000.00
Example
Though the AGE column have the value "25" in two records, each combination of
"25" with it's specific 'salary' is unique, so both rows are included in the result set −
AGE SALARY
22 4500.00
23 2000.00
24 10000.00
25 1500.00
25 6500.00
27 8500.00
32 2000.00
Syntax
Following is the syntax for using the DISTINCT keyword with COUNT() function
−
In the following query, we are retrieving the count of distinct age of the customers
−
UniqueAge
6
Example
First of all let us update two records of the CUSTOMERS table and modify their
salary values to NULL
UPDATE CUSTOMERS SET SALARY = NULL WHERE ID IN(6,4);
Now, we are retrieving the distinct salary of the customers using the following
query −
SALARY
NULL
1500.00
2000.00
8500.00
10000.00
ORDER BY is used with the SQL SELECT statement and is usually specified after
the WHERE, HAVING, and GROUP BY clauses.
This preferred order may not sort the records of a table in any standard order (like
alphabetical or lexicographical), but they could be sorted based on external
condition(s).
For instance, in the CUSTOMERS table containing the details of the customers of
an organization, the records can be sorted based on the population of the cities they
are from. This need not be alphabetically sorted, instead, we need to define the
order manually using the CASE statement.
Syntax
Assume we have created a table with name CUSTOMERS in the MySQL database
using CREATE TABLE statement as shown below −
Following query inserts values into this table using the INSERT statement −
In the following query, we are sorting the records of the CUSTOMERS table in
ascending order based on the column NAME −
Example
The following query sorts the records of the CUSTOMER table based on the
descending order of the name of the customers −
In the following query, we are retrieving all records from the CUSTOMERS table
and sorting them first by their address in ascending order, and then by their salary
in descending order −
Example
Now, we are retrieving all records from the CUSTOMERS table where the age of
the customer is 25, and sorting them as per the descending order of their names −
Syntax
Following is the syntax of using the LIMIT clause with the ORDER BY clause in
MySQL database −
In here, we are retrieving the top 4 records from the CUSTOMERS table based on
their salary, and sorting them in ascending order based on their name −
SALARY
6500.00
8500.00
2000.00
1500.00
To fetch the rows with their own preferred order, the SELECT query used would
be as follows −
The above query sorts the CUSTOMERS table based on the custom order defined
using the CASE statement. Here, we are sorting the records based on the
population of the cities specified in the ADDRESS column.
The main purpose of grouping the records of a table based on particular columns is
to perform calculations on these groups. Therefore, The GROUP BY clause is
typically used with aggregate functions such as SUM(), COUNT(), AVG(),
MAX(), or MIN() etc.
For example, if you have a table named SALES_DATA containing the sales data
with the columns YEAR, PRODUCT, and SALES. To calculate the total sales in
an year, the GROUP BY clause can be used to group the records in this table based
on the year and calculate the sum of sales in each group using the SUM() function.
Syntax
SELECT column_name(s)
FROM table_name
GROUP BY column_name(s);
Where, column_name(s) refers to the name of one or more columns in the table
that we want to group the data by and the table_name refers to the name of the
table that we want to retrieve data from.
Now insert values into this table using the INSERT statement as follows −
The following SQL query groups the CUSTOMERS table based on AGE and
counts the number of records in each group −
AGE COUNT(Name)
32 3
23 2
25 2
Example
In the following query, we are finding the highest salary for each age −
AGE MAX_SALARY
32 6500.00
23 8500.00
25 10000.00
Similarly we can group the records of the CUSTOMERS table based on the AGE
column and calculate the maximum salary, average and sum of the SALARY
values in each group using the MIN(), AVG() and SUM() functions respectively.
GROUP BY Clause on Single Columns
When we use the GROUP BY clause with a single column, all the rows in the table
that have the same value in that particular column will be merged into a single
record.
Example
In the following example we are grouping the above created CUSTOMERS table
by the ADDRESS column and calculating the average salary of the customer from
each city −
ADDRESS AVG_SALARY
Hyderabad 1750.000000
Delhi 4250.000000
Bhopal 8500.000000
Indore 7250.000000
Example
In the following query we are grouping the records of the CUSTOMERS table
based on the columns ADDRESS and AGE and −
Hyderabad 32 3500.00
Delhi 23 2000.00
Delhi 32 6500.00
Bhopal 23 8500.00
Indore 25 14500.00
Syntax
Following is the syntax for using ORDER BY clause with GROUP BY clause in
SQL −
In here, we are finding the highest salary for each age, sorted by high to low −
AGE MIN_SALARY
25 4500.00
23 2000.00
32 1500.00
Syntax
Following is the syntax for using ORDER BY clause with HAVING clause in SQL
−
In the following query, we are grouping the customers by their age and calculating
the minimum salary for each group. Using the HAVING clause we are filtering the
groups where the age is greater than 24 −
Hyderabad 32 1500.00
Delhi 32 6500.00
Indore 25 4500.00
SQL - Having Clause
Moreover, the HAVING clause can be used with aggregate functions such as
COUNT(), SUM(), AVG(), etc., whereas the WHERE clause cannot be used with
them.
Syntax
The following code block shows the position of the HAVING Clause in a query −
SELECT
FROM
WHERE
GROUP BY
HAVING
ORDER BY
Example
Now insert values into this table using the INSERT statement as follows −
Now, we are grouping the records of the CUSTOMERS table based on the
columns ADDRESS and AGE and filtering the groups where the AGE value is less
than 25.
SELECT ADDRESS, AGE, MIN(SALARY) AS MIN_SAL FROM
CUSTOMERS GROUP BY ADDRESS, AGE HAVING AGE > 25;
Output
Hyderabad 32 1500.00
Delhi 32 6500.00
Example
Following query groups the records of the CUSTOMERS table based on the
columns AGE and ADDRESS, filters the groups where the SALARY value is less
than 5000 and, arranges the remaining groups in descending order based the total
salaries of each group.
INDORE 25 14500.00
BHOPAL 23 8500.00
DELHI 32 6500.00
HAVING Clause with COUNT() Function
The HAVING clause can be used with the COUNT() function to filter groups
based on the number of rows they contain.
Example
Following query groups the records of the CUSTOMERS table based on the AGE
column and, retrieves the details of the group that has more than two entities −
AGE COUNT(AGE)
32 3
Example
Now, we are retrieving the city of the customers whose average salary is greater
than 5240 −
ADDRESS AVG_SALARY
Bhopal 8500.000000
Indore 7250.000000
HAVING Clause with MAX() Function
We can also use the HAVING clause with MAX() function to filter groups based
on the maximum value of a specified column.
Example
Now, we are retrieving the city of the customers whose maximum salary is greater
than 5240 −
ADDRESS MAX_SALARY
Bhopal 8500.00
Indore 10000.00
SQL - AND and OR Conjunctive Operators
These operators are used to specify conditions in an SQL statement with the
purpose of filtering data or to serve as conjunctions for multiple conditions in a
statement.
The SQL AND & OR are logical operators, that serve as conjunctive operators,
used to combine multiple conditions in an SQL statement with the purpose of
filtering data in a database table.
The basic syntax of the AND operator with a WHERE clause is as follows −
You can combine N number of conditions using the AND operator. For an action
to be taken by the SQL statement, whether it be a transaction or a query, all
conditions separated by the AND must be TRUE.
Example
Assume we have created a table with name CUSTOMERS in SQL database using
CREATE TABLE statement as shown below −
Following query inserts values into this table using the INSERT statement −
Using the following SELECT query, you can verify if the records are properly
inserted into the table −
Following is an example, which would fetch the ID, Name and Salary fields from
the CUSTOMERS table, where the salary is greater than 2000 and the age is less
than 25 years −
+----+-------+----------+
| ID | NAME | SALARY |
+----+-------+----------+
| 6 | Komal | 4500.00 |
| 7 | Muffy | 10000.00 |
+----+-------+----------+
Example
In the following query, we are selecting all records from the CUSTOMERS table
where the name of the customer starts with 'K', the age of the customer is greater
than or equal to 22, and their salary is less than 3742 −
+----+---------+-----+---------+---------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+---------+-----+---------+---------+
| 2 | Khilan | 25 | Delhi | 1500.00 |
| 3 | kaushik | 23 | Kota | 2000.00 |
+----+---------+-----+---------+---------+
It's important to note that when using multiple logical operators in SQL, the order
of operations is important. Parentheses can be used to control the order of
operations and ensure that the conditions are evaluated in the correct order.
Additionally, using too many logical operators or complex expressions can
negatively impact query performance, so it's important to carefully consider the
design of the WHERE clause when working with large datasets.
Example
In here, we are combining the AND operator with the NOT operator to create
a NAND operation. The 'NAND' operation returns true if at least one of the input
conditions is false, and false if both input conditions are true.
In the following query we are selecting all records from the CUSTOMERS table
where the condition (salary is greater than 4500 and the age is less than 26) is false.
The "NOT" operator negates the entire condition, and the "AND" operator
combines two conditions −
+----+---------+-----+-----------+---------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+---------+-----+-----------+---------+
| 1 | Ramesh | 32 | Ahmedabad | 2000.00 |
| 2 | Khilan | 25 | Delhi | 1500.00 |
| 3 | kaushik | 23 | Kota | 2000.00 |
| 5 | Hardik | 27 | Bhopal | 8500.00 |
| 6 | Komal | 22 | MP | 4500.00 |
+----+---------+-----+-----------+---------+
Syntax
Following is the syntax of using the AND operator with the UPDATE statement −
UPDATE table_name
SET column1 = value1, column2 = value2, ...
WHERE condition1 AND condition2 AND ...;
Where, table_name is the name of the table we want to update, column1,
column2, etc. are the columns we want to modify, and value1, value2, etc. are the
new values we want to set for those columns.
Example
In the following query we are trying to update the salary of all the customers
whose age is greater than 27 and updating it to ‘55000’ using UPDATE statement
−
UPDATE CUSTOMERS
SET salary = 55000
WHERE AGE > 27;
Output
We get the following result. We can observe that the salary of 1 customer has been
modified −
(1 row affected)
Verification
To verify if the changes are reflected in the tables, we can use SELECT statement
to print the tables.
+----+----------+-----+-----------+----------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+----------+-----+-----------+----------+
| 1 | Ramesh | 32 | Ahmedabad | 55000.00 |
| 2 | Khilan | 25 | Delhi | 1500.00 |
| 3 | kaushik | 23 | Kota | 2000.00 |
| 4 | Chaitali | 25 | Mumbai | 6500.00 |
| 5 | Hardik | 27 | Bhopal | 8500.00 |
| 6 | Komal | 22 | MP | 4500.00 |
| 7 | Muffy | 24 | Indore | 10000.00 |
+----+----------+-----+-----------+----------+
As we can see in the above table, the salary of ‘Ramesh’ has been updated to
‘55000’ because his age is 32 i.e. greater than 27.
The OR Operator
The OR operator is used to combine multiple conditions in an SQL statement's
WHERE clause. It returns true if at least one of the conditions is true, and false if
all conditions are false.
Syntax
You can combine N number of conditions using the OR operator. For an action to
be taken by the SQL statement, whether it be a transaction or query, the only any
ONE of the conditions separated by the OR must be TRUE.
Example
The following query fetches the ID, Name and Salary fields from the
CUSTOMERS table, where the salary is greater than 2000 OR the age is less than
25 years.
+----+----------+----------+
| ID | NAME | SALARY |
+----+----------+----------+
| 3 | kaushik | 2000.00 |
| 4 | Chaitali | 6500.00 |
| 5 | Hardik | 8500.00 |
| 6 | Komal | 4500.00 |
| 7 | Muffy | 10000.00 |
+----+----------+----------+
Multiple OR operators
In SQL, it is common to use multiple 'OR' operators to combine multiple
conditions or expressions together. When using multiple "OR" operators, any rows
that meet at least one of the conditions will be returned.
Example
In the following query, we are selecting all records from the CUSTOMERS table
where either the name of the customer ends with 'l', or the salary of the customer is
greater than 10560, or their age is less than 25 −
+----+---------+-----+---------+---------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+---------+-----+---------+---------+
| 3 | kaushik | 23 | Kota | 2000.00 |
| 6 | Komal | 22 | MP | 4500.00 |
| 7 | Muffy | 24 | Indore |10000.00 |
+----+---------+-----+---------+---------+
Syntax
Following is the syntax for using the AND and OR operators together −
In the following query we are trying to retrieve all rows from the "CUSTOMERS"
table where the age is equal to 25 or the salary is less than 4500 and the name is
either Komal or Kaushik. The parentheses control the order of evaluation so that
the OR operator is applied first, followed by the AND operator −
+----+----------+-----+-----------+----------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+----------+-----+-----------+----------+
| 3 | kaushik | 23 | Kota | 2000.00 |
+----+----------+-----+-----------+----------+
OR with DELETE statement
We can also use the OR operator with the DELETE statement to delete rows that
meet any one of multiple conditions.
Syntax
In the following query we are trying to delete the records from the customers table
where either the age of the customer equals 25 or their salary is less than 2000 −
(2 rows affected)
Verification
To verify if the changes are reflected in the tables, we can use SELECT statement
to print the tables.
+----+----------+-----+-----------+----------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+----------+-----+-----------+----------+
| 1 | Ramesh | 32 | Ahmedabad | 55000.00 |
| 3 | kaushik | 23 | Kota | 2000.00 |
| 5 | Hardik | 27 | Bhopal | 8500.00 |
| 6 | Komal | 22 | MP | 4500.00 |
| 7 | Muffy | 24 | Indore | 10000.00 |
+----+----------+-----+-----------+----------+
SQL - LIKE Operator
The SQL LIKE is a logical operator that is used to retrieve the data in a column of
a table, based on a specified pattern.
It is used along with the WHERE clause of the UPDATE, DELETE and SELECT
statements, to filter the rows based on the given pattern. These patterns are
specified using ‘Wildcards’.
Suppose we need to submit the list of all the students whose name starts with ‘K’.
We can obtain this with the help of the LIKE operator as follows −
%
1
The percent sign represents zero, one or multiple characters.
_
2
The underscore represents a single number or character.
[]
3
This matches any single character within the given range in the [].
4 [^]
This matches any single character excluding the given range in the [^].
Note − In the LIKE operator, the above wildcard characters can be used
individually as well as in combinations with each other. The two mainly used
wildcard characters are ‘%’ and ‘_’.
The table given below has a few examples showing the WHERE clause having
different LIKE operators with '%' , '_' , [] and [^] pattern −
To understand it better let us consider the CUSTOMERS table which contains the
personal details of customers including their name, age, address and salary etc. as
shown below −
Now, insert values into this table using the INSERT statement as follows −
+----+----------+-----+-----------+----------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+----------+-----+-----------+----------+
| 1 | Ramesh | 32 | Ahmedabad | 2000.00 |
| 2 | Khilan | 25 | Delhi | 1500.00 |
| 3 | kaushik | 23 | Kota | 2000.00 |
| 4 | Chaitali | 25 | Mumbai | 6500.00 |
| 5 | Hardik | 27 | Bhopal | 8500.00 |
| 6 | Komal | 22 | MP | 4500.00 |
| 7 | Muffy | 24 | Indore | 10000.00 |
+----+----------+-----+-----------+----------+
Now, let us try to display all the records from the CUSTOMERS table, where the
SALARY starts with 200.
+----+---------+-----+-----------+---------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+---------+-----+-----------+---------+
| 1 | Ramesh | 32 | Ahmedabad | 2000.00 |
| 3 | kaushik | 23 | Kota | 2000.00 |
+----+---------+-----+-----------+---------+
Example
Below is the query, that displays all the records from the CUSTOMERS table
previously created, with the NAME that has ‘al’ in any position. Here we are using
multiple ‘%’ wildcards in the LIKE condition −
+----+----------+-----+---------+---------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+----------+-----+---------+---------+
| 4 | Chaitali | 25 | Mumbai | 6500.00 |
| 6 | Komal | 22 | MP | 4500.00 |
+----+----------+-----+---------+---------+
+----+---------+-----+---------+---------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+---------+-----+---------+---------+
| 2 | Khilan | 25 | Delhi | 1500.00 |
| 3 | kaushik | 23 | Kota | 2000.00 |
| 6 | Komal | 22 | MP | 4500.00 |
+----+---------+-----+---------+---------+
Example
Following is the query to display all the records from the CUSTOMERS table,
where the Name has ‘m’ in the third position −
+----+--------+-----+-----------+---------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+--------+-----+-----------+---------+
| 1 | Ramesh | 32 | Ahmedabad | 2000.00 |
| 6 | Komal | 22 | MP | 4500.00 |
+----+--------+-----+-----------+---------+
Example
In the query given below we are trying to display all the records from the
CUSTOMERS table, where the NAME starts with K and has the specified
characters set [h,i,o,m,l,a,n] −
select * from customers
where NAME LIKE 'k[h,i,o,m,l,a,n]%';
SELECT *
FROM customers
WHERE NAME LIKE 'k%'
AND (NAME LIKE 'kh%'
OR NAME LIKE 'ki%'
OR NAME LIKE 'ko%'
OR NAME LIKE 'km%'
OR NAME LIKE 'kl%'
OR NAME LIKE 'ka%'
OR NAME LIKE 'kn%');
Output
+----+----------+-----+-----------+----------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+----------+-----+-----------+----------+
| 2 | Khilan | 25 | Delhi | 1500.00 |
| 3 | kaushik | 23 | Kota | 2000.00 |
| 6 | Komal | 22 | MP | 4500.00 |
+----+----------+-----+-----------+----------+
Example
In MySQL, you can use the REGEXP operator with a regular expression to achieve the
desired pattern matching where the NAME column starts with any character from 'b' to 'i'.
Here's how you can write the query:
SELECT *
FROM customers
WHERE NAME REGEXP '^[b-i]';
Output
+----+----------+-----+-----------+----------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+----------+-----+-----------+----------+
| 4 | Chaitali | 25 | Mumbai | 6500.00 |
| 5 | Hardik | 27 | Bhopal | 8500.00 |
+----+----------+-----+-----------+----------+
Using the “[^]” wildcard character
The [^ character list or range] matches any single character that is not present in
the given range or character list.
Example
In MySQL, you can use the REGEXP operator with a regular expression to achieve the
desired pattern matching where the NAME column does not start with any character from 'b'
to 'k'. Here's how you can write the query:
SELECT *
FROM customers
WHERE NAME NOT REGEXP '^[b-k]';
Output
+----+----------+-----+-----------+----------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+----------+-----+-----------+----------+
| 1 | Ramesh | 32 | Ahmedabad | 2000.00 |
| 7 | Muffy | 24 | Indore | 10000.00|
+----+----------+-----+-----------+----------+
Example
Here, the SQL command select the customers whose NAME starts with C and
ends with i, or customers whose NAME ends with k −
SELECT * FROM CUSTOMERS
WHERE NAME LIKE 'C%i' OR NAME LIKE '%k';
Output
+----+----------+-----+---------+---------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+----------+-----+---------+---------+
| 3 | kaushik | 23 | Kota | 2000.00 |
| 4 | Chaitali | 25 | Mumbai | 6500.00 |
| 5 | Hardik | 27 | Bhopal | 8500.00 |
+----+----------+-----+---------+---------+
Syntax
+----+----------+-----+-----------+----------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+----------+-----+-----------+----------+
| 1 | Ramesh | 32 | Ahmedabad | 2000.00 |
| 4 | Chaitali | 25 | Mumbai | 6500.00 |
| 5 | Hardik | 27 | Bhopal | 8500.00 |
| 7 | Muffy | 24 | Indore | 10000.00 |
+----+----------+-----+-----------+----------+
The syntax for using the LIKE operator with escape characters is as follows −
Where,
Now, we can insert values into this empty tables using the INSERT statement as
follows −
+----------+---------------+
| SALARY | BONUS_PERCENT |
+----------+---------------+
| 54000.00 | 20.34% |
| 84000.00 | 56.82% |
+----------+---------------+
Example
In here, we are trying to return the BONUS_PERCENT that starts with ‘2’ and
contains the ‘%’ literal.
select * from employee
WHERE BONUS_PERCENT LIKE'2%!%%' escape '!';
Output
+----------+---------------+
| SALARY | BONUS_PERCENT |
+----------+---------------+
| 54000.00 | 20.34% |
+----------+---------------+
SQL - IN Operator
The SQL IN is a logical operator that allows us to specify multiple values or sub
query in the WHERE clause.
It returns all rows in which the specified column matches one of the values in the
list. The list of values or sub query must be specified in the parenthesis e.g.
IN (select query) or IN (Value1, Value2, Value3, …).
The IN operator can be used with any data type in SQL. It is used to filter data
from a database table based on specified values.
The IN operator is useful when you want to select all rows that match one of a
specific set of values. While the OR operator is useful when you want to select all
rows that match any one of multiple conditions.
Syntax
The basic syntax of the SQL IN operator to specify multiple values is as follows −
Where,
value1, value2, value3, … are the values in the list to be tested against the
expression. The IN operator returns TRUE if any of these values is found in
the list, and FALSE if it is not.
Example
To understand it better let us consider the CUSTOMERS table which contains the
personal details of customers including their name, age, address and salary etc. as
shown below −
CREATE TABLE CUSTOMERS (
ID INT NOT NULL,
NAME VARCHAR (20) NOT NULL,
AGE INT NOT NULL,
ADDRESS CHAR (25),
SALARY DECIMAL (18, 2),
PRIMARY KEY (ID)
);
Now, insert values into this table using the INSERT statement as follows −
+----+----------+-----+-----------+----------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+----------+-----+-----------+----------+
| 1 | Ramesh | 32 | Ahmedabad | 2000.00 |
| 2 | Khilan | 25 | Delhi | 1500.00 |
| 3 | kaushik | 23 | Kota | 2000.00 |
| 4 | Chaitali | 25 | Mumbai | 6500.00 |
| 5 | Hardik | 27 | Bhopal | 8500.00 |
| 6 | Komal | 22 | MP | 4500.00 |
| 7 | Muffy | 24 | Indore | 10000.00 |
+----+----------+-----+-----------+----------+
Suppose based on the above table we want to display records with NAME equal to
‘Khilan’, ‘Hardik’ and ‘Muffy’ (string values). This can be achieved
using IN operator as follows −
select * from CUSTOMERS WHERE NAME IN ('Khilan', 'Hardik', 'Muffy');
Output
+----+--------+-----+---------+----------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+--------+-----+---------+----------+
| 2 | Khilan | 25 | Delhi | 1500.00 |
| 5 | Hardik | 27 | Bhopal | 8500.00 |
| 7 | Muffy | 24 | Indore | 10000.00 |
+----+--------+-----+---------+----------+
Note − We cannot use the wildcard characters '%', '_', etc. with the string values.
The above query can also be done using OR operator as follows −
select * from CUSTOMERS WHERE NAME = 'Khilan' OR NAME = 'Hardik' OR
NAME = 'Muffy';
Output
+----+--------+-----+---------+----------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+--------+-----+---------+----------+
| 2 | Khilan | 25 | Delhi | 1500.00 |
| 5 | Hardik | 27 | Bhopal | 8500.00 |
| 7 | Muffy | 24 | Indore | 10000.00 |
+----+--------+-----+---------+----------+
Here, we are using the IN operator to specify multiple values in the UPDATE
statement and updating the CUSTOMERS table previously created. Here, are
changing the records of the customers with age ‘25’ or ‘27’ and updating the age
value to ‘30’ −
We get the following result. We can observe that the age of 3 customers has been
modified −
(3 rows affected)
Verification
We can verify whether the changes are reflected in a table by retrieving its contents
using the SELECT statement. Following is the query to display the records in the
Customers table −
+----+----------+-----+-----------+----------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+----------+-----+-----------+----------+
| 1 | Ramesh | 32 | Ahmedabad | 2000.00 |
| 2 | Khilan | 30 | Delhi | 1500.00 |
| 3 | kaushik | 23 | Kota | 2000.00 |
| 4 | Chaitali | 30 | Mumbai | 6500.00 |
| 5 | Hardik | 30 | Bhopal | 8500.00 |
| 6 | Komal | 22 | MP | 4500.00 |
| 7 | Muffy | 24 | Indore | 10000.00 |
+----+----------+-----+-----------+----------+
As we can see in the above table, the AGE of ‘Khilan’, ‘Chaitali’ and ‘Hardik’ has
been updated to ‘30’.
Syntax
Now, we are trying to display all the records from the CUSTOMERS table, where
the AGE is NOT equal to ‘25’, ‘23’ and ‘22’ −
+----+--------+-----+-----------+----------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+--------+-----+-----------+----------+
| 1 | Ramesh | 32 | Ahmedabad | 2000.00 |
| 5 | Hardik | 27 | Bhopal | 8500.00 |
| 7 | Muffy | 24 | Indore | 10000.00 |
+----+--------+-----+-----------+----------+
Example
In the below query, we are trying to select the rows with the value of thSALARY
column −
+----+---------+-----+-----------+---------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+---------+-----+-----------+---------+
| 1 | Ramesh | 32 | Ahmedabad | 2000.00 |
| 3 | kaushik | 23 | Kota | 2000.00 |
+----+---------+-----+-----------+---------+
Syntax
Where,
Subquery − This is the SELECT statement that has a result set to be tested
against the expression. The IN condition evaluates to true if any of these
values match the expression.
Example
In the query given below we are displaying all the records from the CUSTOMERS
table where the NAME of the customer is obtained with SALARY greater than
2000 −
+----+----------+-----+---------+----------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+----------+-----+---------+----------+
| 4 | Chaitali | 25 | Mumbai | 6500.00 |
| 5 | Hardik | 27 | Bhopal | 8500.00 |
| 6 | Komal | 22 | MP | 4500.00 |
| 7 | Muffy | 24 | Indore | 10000.00 |
+----+----------+-----+---------+----------+