SQL Queries
SQL Queries
What is SQL?
SQL language is divided into four types of primary language statements: DML, DDL, DCL
and TCL.
These are basic operations we perform on data such as selecting a few records from a
existing records.
DDL statements are used to alter/modify a database or table structure and schema.
DCL statements control the level of access that users have on database objects.
TCL statements allow you to control and manage transactions to maintain the integrity of
data within SQL statements.
Syntax:
FROM table_name;
Example:
The SELECT DISTINCT statement is used to return only distinct (different) values.
Syntax:
FROM table_name;
Example:
The WHERE clause is used to filter records. The WHERE clause is used to extract only those
records that fulfill a specified condition.
Syntax:
Example:
Syntax:
Example:
Syntax:
Example:
Syntax :
Example:
= Equal
The BETWEEN operator selects values within a given range. The values can be
numbers, text, or dates
Syntax:
SELECT column_name(s)
FROM table_name
WHERE column_name BETWEEN value1 AND value2;
Example:
Example:
Example:
AND ‘CLERK’ ;
BETWEEN (Date)
Example1:
Example2:
Syntax:
SELECT column_name(s)
FROM table_name
WHERE column_name IN (value1, value2, ...);
OR
SELECT column_name(s)
FROM table_name
WHERE column_name IN (SELECT STATEMENT);
IN Operator
Example1
Example2
The LIKE operator is used in a WHERE clause to search for a specified pattern in a
column.
WHERE ENAME LIKE ‘A%' Finds any values that starts with ‘A’.
WHERE ENAME LIKE '%A' Finds any values that ends with ‘A’.
WHERE ENAME LIKE ‘%M%' Finds any values that have ‘M’ in any position.
WHERE ENAME LIKE '_A%' Finds any values that have ‘A’ in the second position.
WHERE ENAME LIKE ‘A%O' Finds any values that starts with ‘A’ and ends with ‘O’.
LIKE Operator
Syntax:
Example
Syntax:
Example:
Syntax:
Example
Syntax:
Example:
Syntax:
Example
Syntax:
Example
Example
Syntax:
UPDATE table_name
SET column1 = value1, column2 = value2, ...
WHERE condition;
Example
UPDATE Customers
SET CustomerName = 'Ahmad', City= ‘LHR'
WHERE CustomerID = 1;
DELETE Statement
Syntax:
Example
Syntax:
SELECT column_names
FROM table_name
WHERE column_name IS NULL;
Example
Syntax:
SELECT column_names
FROM table_name
WHERE column_name IS NOT NULL;
Example
Syntax:
Example
SELECT CustomerName, Address + ', ' + PostalCode + ' ' + City + ', ' +
Country AS Address FROM Customers;
GROUP BY Statement
The GROUP BY statement is often used with aggregate functions (COUNT, MAX, MIN,
SUM, AVG) to group the result-set by one or more columns
Syntax:
SELECT column_name(s)
FROM table_name
WHERE condition
GROUP BY column_name(s)
ORDER BY column_name(s);
GROUP BY Statement
Example:
The HAVING clause was added to SQL because the WHERE keyword could not be used
with aggregate functions.
Example:
FROM Customers
GROUP BY Country