SQL Query
SQL Query
SQL Query
1) SELECT QUERY:
Select Column1, Column2 from table_name;
Select difficult value from the table, ie ignore the duplicate values from the table use Select distinct
query.
The Where clause used to extract the only records which fulfil the specific requirements.
Syntax:
The Where condition not only used with “select” statement and also possible to use “update”,”Delete”,
etc.,
SQL Requires Single Quotes around the Text values( where other systems are required double Quotes).
Syntax:
Operator Description
‘> Greater than Example: SELECT * FROM Products WHERE Price > 30;
Operator Description
< Less Than Example: SELECT * FROM Products WHERE Price < 30;
Operator Description
>= Greater than or equal to Example: SELECT * FROM Products WHERE Price >= 30;
Operator Description
<= Less than or Equal to Example : SELECT * FROM Products WHERE Price <= 30;
Operator Description
‘ <> Not Equal to Example: SELECT * FROM Products WHERE Price <> 18;
Operator Description
Between Between Certain Range Example: SELECT * FROM Products WHERE Price BETWEEN 50 AND 60;
Operator Description
Like Like Pattern Example: SELECT * FROM Customers WHERE City LIKE 's%';
Operator Description
The Where Clauses are shall be combined with AND, OR and NOT Operators.
The AND and OR operators are used to filter records based on the more than one condition.
The AND Operators displays the records if all the conditions are TRUE.
The OR Operators displays the records if any one of conditions are TRUE.
The NOT operators displays a records if the conditions are not TRUE.
AND Syntax:
SELECT column1, column2, ...FROM table_name
WHERE condition1 AND condition2 AND condition3 ...;
OR Syntax:
SELECT column1, column2, ...FROM table_name
WHERE condition1 OR condition2 OR condition3 ...;
NOT Syntax:
The Order by keyword is used to sort the Result –set in ascending or descending Order by keyword
Default sort in Ascending order. If we want to sort in descending order, use DESC Keyword.
Order by Syntax:
SELECT column1, column2, ...
FROM table_name
ORDER BY column1, column2, ... ASC|DESC;
SELECT * FROM Customers
ORDER BY Country ASC, CustomerName DESC;
ii) If you are adding the values to the all columns in the table no need to specify the column name.
use the following syntax.
INSERT INTO table_name VALUES (value1, value2, value3, ...);
7) SQL NULL Values:
To Test the Null Value cant able to use the comparative operators, we shall use the “IS NULL” or “IS
NOT NULL” Operator instead.
IS NULL Syntax:
8) UPDATE Statement:
The Update statement used to modify the existing records in the table.
Update syntax:
UPDATE table_name
SET column1 = value1, column2 = value2, ...
WHERE condition;
9) DELETE statement:
The Delete statement used to delete the Records from the table,
DELETE Syntax:
DELETE FROM table_name WHERE condition;
To Delete All Records from the Table without alter the table structure.
DELETE FROM table_name;
Example: SELECT TOP 50 PERCENT * FROM Customers;
Or
SELECT TOP 3 * FROM Customers;
SELECT TOP 3 * FROM Customers WHERE Country='Germany';
The MIN() function return the Minimum values from the column.
The MAX() function return the Maximum values from the column.
MIN() Syntax:
MAX() Syntax:
SELECT MAX(column_name)FROM table_name WHERE condition;
The Count Function returns the Number of Rows which fullful the specific condition.
The AVG function returns the average values of the Numeric Column.
COUNT() Syntax:
SELECT COUNT(column_name)FROM table_name WHERE condition;
AVG() Syntax:
SUM() Syntax:
LIKE Syntax:
SELECT column1, column2, ...FROM table_name WHERE columnN LIKE pattern;
Examples:
WHERE CustomerName LIKE Finds any values that start with "a"
'a%'
WHERE CustomerName LIKE Finds any values that end with "a"
'%a'
WHERE CustomerName LIKE Finds any values that have "or" in any position
'%or%'
WHERE CustomerName LIKE Finds any values that have "r" in the second position
'_r%'
WHERE CustomerName LIKE Finds any values that start with "a" and are at least 3
'a__%' characters in length
WHERE ContactName LIKE 'a Finds any values that start with "a" and ends with "o"
%o'
Wildcard characters are used with SQL LIKE operator. The LIKE Operator is used in a WHERE clause to
search for Specified pattern in a column.
Wildcard Characters in SQL Server
% Represents zero or more characters bl% finds bl, black, blue, and
blob
[] Represents any single character within h[oa]t finds hot and hat, but
the brackets not hit
^ Represents any character not in the h[^oa]t finds hit, but not hot
brackets and hat
Or
SELECT column_name(s)
FROM table_name
WHERE column_name IN (SELECT STATEMENT);
Example:
SELECT * FROM Customers
WHERE Country NOT IN ('Germany', 'France', 'UK');
SELECT * FROM Customers
WHERE Country IN (SELECT Country FROM Suppliers);
The BETWEEN Operator is inclusive : begin and end values are included.
BETWEEN Syntax:
SELECT column_name(s) FROM table_name
WHERE column_name BETWEEN value1 AND value2;
Example:
select freight from Orders where Freight not Between 10 and 20;
SQL Aliases are used to give a table , or a column in a table , a temporary name.
SELECT column_name AS alias_name
FROM table_name;
SELECT column_name(s)
FROM table_name AS alias_name;
If Alias contain Space then mention the Alias name between Square bracket ex: [contact Name]
Example:
A JOIN Clause used to combine rows from two or more tables , based on the related column between them.
INNER JOIN: Returns records that have matching values in both tables.
LEFT(OUTTER) JOIN: Returns All the records from the LEFT table and matched records from Right
table.
RIGHT (OUTTER)JOIN: Returns All the Records from the RIGHT Table and matched records from LEFT
Table.
FULL(OUTTER) JOIN: Returns all the records from the Both the table if values matched either in
Right table or left table.
Example:
SELECT Orders.OrderID, Customers.CustomerName, Orders.OrderDate
FROM Orders
INNER JOIN Customers ON Orders.CustomerID=Customers.CustomerID;
The LEFT JOIN Keyword returns all records from the left table(table1), and the matched records from
the right table(table2). The Result is NULL from the Right side, if there is no match.
Example:
SELECT Orders.OrderID, Customers.CustomerName, Shippers.ShipperName
FROM ((Orders
LEFT OUTER JOIN Customers ON Orders.CustomerID = Customers.CustomerID)
LEFT OUTER JOIN Shippers ON Orders.ShipperID = Shippers.ShipperID);
21) RIGHT JOIN Keyword:
The LEFT JOIN Keyword returns all records from the left table(table1), and the matched records
from the right table(table2). The Result is NULL from the Right side, if there is no match.
SELECT column_name(s)
FROM table1
RIGHT JOIN table2
ON table1.column_name = table2.column_name;
Example:
SELECT Orders.OrderID, Customers.CustomerName, Shippers.ShipperName
FROM ((Orders
RIGHT OUTER JOIN Customers ON Orders.CustomerID = Customers.CustomerID)
RIGHT OUTER JOIN Shippers ON Orders.ShipperID = Shippers.ShipperID);
The FULL JOIN Keyword Returns all the records when there is match in left (table1) or right (table2)
table records.
SELECT column_name(s)
FROM table1
FULL OUTER JOIN table2
ON table1.column_name = table2.column_name
WHERE condition;
Example:
SELECT Customers.CustomerName, Orders.OrderID
FROM Customers
FULL OUTER JOIN Orders ON Customers.CustomerID=Orders.CustomerID
ORDER BY Customers.CustomerName;
Example:
SELECT A.CustomerName AS CustomerName1,
B.CustomerName AS CustomerName2, A.City
FROM Customers A, Customers B
WHERE A.CustomerID <> B.CustomerID
AND A.City = B.City
ORDER BY A.City;
The UNION operator is used to combine the result- set of two or more SELECT Statements.
Each SELECT Statement within UNION must have same numbers of Columns.
The Columns must also have similar Data types.
The Columns in Each SELECT Statement must also be in same orders.
UNION Syntax:
SELECT column_name(s) FROM table1
UNION
SELECT column_name(s) FROM table2;
Example:
SELECT column_name(s) FROM table1
UNION ALL
SELECT column_name(s) FROM table2;
SELECT City, Country FROM Customers
WHERE Country='Germany'
UNION
SELECT City, Country FROM Suppliers
WHERE Country='Germany'
ORDER BY City;
UNION Operator only selects the Distinct values by Default. But we require duplicate values also, then
Use UNION ALL
SELECT column_name(s) FROM table1
UNION ALL
SELECT column_name(s) FROM table2;
Example:
SELECT City FROM Customers
UNION ALL
SELECT City FROM Suppliers
ORDER BY City;
SELECT City, Country FROM Customers
WHERE Country='Germany'
UNION ALL
SELECT City, Country FROM Suppliers
WHERE Country='Germany'
ORDER BY City;
Example:
SELECT COUNT(CustomerID), Country
FROM Customers
GROUP BY Country;
Having Clause was added to SQL because the WHERE Keyword could not be used in aggregate functions.
HAVING Syntax:
SELECT column_name(s)
FROM table_name
WHERE condition
GROUP BY column_name(s)
HAVING condition
ORDER BY column_name(s);
Example:
The Exists operator is used to test for the existence of any record in a subquery.
The Exists Operator Returns True if the subquery returns one or more records.
EXISTS Syntax:
SELECT column_name(s)
FROM table_name
WHERE EXISTS
(SELECT column_name FROM table_name WHERE condition);
Example:
The ANY and ALL Operators are used with a WHERE or HAVING Clause.
The ANY Operator returns true if any of the sub query values meet the condition.
The ALL Operator returns true if all of the sub query values meet the condition.
Note: The operator must be a standard comparison operator (=, <>,!=, >, >=, <, or <=).
ANY Syntax:
SELECT column_name(s)
FROM table_name
WHERE column_name operator ANY
(SELECT column_name FROM table_name WHERE condition);
Description:
The following SQL statement returns TRUE and lists the product names if it finds ANY records in the
OrderDetails table that quantity = 10:
Example:
ALL Syntax:
SELECT column_name(s)
FROM table_name
WHERE column_name operator ALL
(SELECT column_name FROM table_name WHERE condition);
Description:
The following SQL statement returns TRUE and lists the product names if it finds ALL records in the
OrderDetails table that quantity = 10:
Example:
Example:
Copies the Content of Orders and create backup of orders in Order1 Table in same database.
Copies particular Columns from the table and create new table.
SELECT column1, column2, column3, ...
INTO newtable [IN externaldb]
FROM oldtable
WHERE condition;
Example:
To Copies the Table Schema not the data, we shall use the following code,
To Copies the data from More than one table we shall use the following code,
INSERT INTO table2
SELECT * FROM table1
WHERE condition;
Example:
Copy only some columns from one table into another table.
The Case Statement goes through conditions and returns a value when the first condition is met(like an
IF-THEN-ELSE Statement).so, once a condition TRUE, it will stop reading the Result. If no conditions are
TRUE , it returns the value in the ELSE Clause.
CASE Syntax:
CASE
WHEN condition1 THEN result1
WHEN condition2 THEN result2
WHEN conditionN THEN resultN
ELSE result
END;
Example:
select OrderID,Quantity,
CASE
When Quantity > 30 then 'The Quantity is Greater than 30'
When Quantity = 30 then 'The Quantity is 30'
Else 'The Quantity is under 30'
End As QuantityText
from [Order Details]
select CustomerID,ShipCountry,
CASE
When Freight >20.0 then 'Freight is greater than 20'
when Freight =20 then 'Freight is equal to 20'
Else 'Freight is under 20'
End
from Orders
A Stored Procedure is a prepared SQL Code that you can save, so the code can be reused over and over
again. So if you have an SQL query that you write over and over again, save it as stored procedure and
then just call it to execute it.
You can also pass parameters to a stored procedure, so that the stored procedure can act based on the
parameter values that is passed.
CREATE PROCEDURE procedure_name
AS
sql_statement
GO;
Example:
Example:
exec SelectAllCustomers
Example:
Example:
To ignore the Part of Line from the Code /* ,*/ code shall be used.
Example:
SELECT CustomerName, /*City,*/ Country FROM Customers;
Syntax:
Example:
The Backup database statement is used in SQL server to create a full backup of an existing SQL
database.
Syntax:
BACKUP DATABASE databasename
TO DISK = 'filepath';
Example:
A differential database backup only backups the database that have changed since the last full database
backup.
Syntax:
BACKUP DATABASE databasename
TO DISK = 'filepath'
WITH DIFFERENTIAL;
Example:
Syntax:
CREATE TABLE table_name (
column1 datatype,
column2 datatype,
column3 datatype,
....);
The Column Parameters Specify the names of the column of the table.
The datatype parameter specifies the type of data column can hold (e.g: varchar, integer,date etc)
Example:
Use master
Drop table Persons1;
The TRUNCATE TABLE statement is used to delete the data inside a table, not the table itself.
Syntax:
Example:
use Northwind
Truncate Table SupplierNew;
The Alter Table Statement is used to add, delete, or modify the columns in an existing table.
The Alter table statement is used to add and drop various constraints on the existing tables.
Syntax:
ALTER TABLE table_name
ADD column_name datatype;
Example:
ALTER TABLE table_name
DROP COLUMN column_name;
Example:
To Change the data type of a column in a table, use the following syntax:
ALTER TABLE table_name
ALTER COLUMN column_name datatype;
Example:
Constraints can be specified when the table is created with CREATE TABLE Statement , or after
the table is created with the ALTER TABLE Statement.
SQL Constraints are used to specify rules for the data in the table:
Constraints are used to limit the type of data that can go into a table. This Ensures the accuracy
& Reliability of the data in the table. if there is any violation between the constraints and the
data action , the action is aborted.
The Constraint can be column level or table level. Column level constraints apply to Columns
and Table level constraints apply to the whole table.
Syntax:
CREATE TABLE table_name (
column1 datatype constraint,
column2 datatype constraint,
column3 datatype constraint,
....
);
Example:
By Default , a column can hold NULL Value.The NOT NULL Constraint enforces a column to NOT accept the
NULL Values.
NOT NULL on CREATE TABLE:
CREATE TABLE Persons (
ID int NOT NULL,
LastName varchar(255) NOT NULL,
FirstName varchar(255) NOT NULL,Age int);
ALTER TABLE Persons
MODIFY Age int NOT NULL;
The Unique constraint ensures that all values in a column are different.
Both the UNIQUE and PRIMARY KEY Constraint provide the gurantee for uniqueness for a column or set of
column.
CREATE TABLE Persons (
ID int NOT NULL UNIQUE,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Age int
);
ALTER TABLE Persons
ADD UNIQUE (ID);
Example:
To Apply Unique constraint to multiple columns & Name the Unique Constraint the following statement shall be
used.
ALTER TABLE Persons
ADD CONSTRAINT UC_Person UNIQUE (ID,LastName);
Example:
ALTER TABLE Persons
DROP CONSTRAINT UC_Person;
To Allow naming of Primary key constraint and for defining a PRIMARY KEY constraint on multiple
columns, use the following Syntax:
in the above example there is only one primary key (PK_Person2). However the value of the Primary key
is made up of Two Columns(ID +LastName);
A Foreign key is a field in one table refers to the Primary key in another table.
To Allow the Naming of Foreign key constraint and for defining a foreign key
constriant to multiple column use the following SQL code,
To Allow the naming of check constriant and defining for multiple columns , use the
following SQL Code,
To Allow naming of Constraint and for defining in mulitple columns the following
code shall be used,
The Default Constraint can also be used to insert system values , by using functions like GETDATE();
Alter table person2 add constraint df_city default 'Dindigul' for City;
Example:
Create index idx_Lastname on Person1(LasstName);
Create index with combination of Columns use the following type of code:
);
Example:
Dropping a view:
drop view [Brazil Customer];