Download as txt, pdf, or txt
Download as txt, pdf, or txt
You are on page 1of 5

Return data from the Customers table:

SELECT CustomerName, City FROM Customers;

DISTINCT keyword is used to return unique values:


SELECT DISTINCT Country FROM Customers;

The WHERE clause is used to filter records.


SELECT * FROM Customers
WHERE Country='Mexico';

The ORDER BY keyword is used to sort the result-set in ascending or descending


order.
SELECT * FROM Products
ORDER BY Price;

The AND operator is used to filter records based on more than one condition
The WHERE clause can contain one or many AND operators.
SELECT *
FROM Customers
WHERE Country = 'Spain' AND CustomerName LIKE 'G%';

The OR operator is used to filter records based on more than one condition
The WHERE clause can contain one or many OR operators.
SELECT *
FROM Customers
WHERE Country = 'Germany' OR Country = 'Spain';

The NOT operator is used in combination with other operators to give the opposite
resul
SELECT * FROM Customers
WHERE NOT Country = 'Spain';

NOT LIKE
SELECT * FROM Customers
WHERE CustomerName NOT LIKE 'A%';

NOT BETWEEN
SELECT * FROM Customers
WHERE CustomerID NOT BETWEEN 10 AND 60;

NOT IN
SELECT * FROM Customers
WHERE City NOT IN ('Paris', 'London');

NOT Greater Than


SELECT * FROM Customers
WHERE NOT CustomerID > 50;

INSERT INTO statement is used to insert new records in a table.


1. Specify both the column names and the values to be inserted:

INSERT INTO table_name (column1, column2, column3, ...)


VALUES (value1, value2, value3, ...);

2. If adding values for ALL COLUMNS of the table


* No need to specify the column names
* Maintain same order as the columns in the table

INSERT INTO table_name


VALUES (value1, value2, value3, ...);

A field with a NULL value is a field with no value.


Test for NULL Values with IS NULL or IS NOT NULL keywords
SELECT column_names
FROM table_name
WHERE column_name IS NULL;

The UPDATE statement is used to modify the existing records in a table.


UPDATE Customers
SET ContactName = 'Alfred Schmidt', City= 'Frankfurt'
WHERE CustomerID = 1;

The DELETE statement is used to delete existing records in a table.


DELETE FROM table_name WHERE condition;

The SELECT TOP clause or LIMIT is used to specify the number of records to return.
SELECT TOP 3 * FROM Customers;
SELECT * FROM Customers LIMIT 3;

FUNCTIONS
The MIN() function returns the smallest value of the selected column.
The MAX() function returns the largest value of the selected column.
The COUNT() function returns the number of rows that matches a specified criterion.
The SUM() function returns the total sum of a numeric column.
The AVG() function returns the average value of a numeric column.

The LIKE operator is used in a WHERE clause to search for a specified pattern in a
column.
Wildcards used with LIKE operator:
% Represents zero or more characters
_ Represents a single character
SELECT * FROM Customers
WHERE CustomerName LIKE '_a%'

BETWEEN operator selects values within a given range


SELECT * FROM Products
WHERE Price BETWEEN 10 AND 20;
WHERE ProductName BETWEEN 'Carnarvon Tigers' AND 'Mozzarella di Giovanni'
WHERE OrderDate BETWEEN '1996-07-01' AND '1996-07-31';
WHERE OrderDate BETWEEN #07/01/1996# AND #07/31/1996#;

SQL Aliases - temporary name for table or column. Make more readable.

SELECT CustomerName, CONCAT(Address,', ',PostalCode,', ',City,', ',Country) AS


Address
FROM Customers;

JOIN clause is used to combine rows from two or more tables, based on a related
column between them
SELECT Orders.OrderID, Customers.CustomerName, Orders.OrderDate
FROM Orders
INNER JOIN Customers ON Orders.CustomerID=Customers.CustomerID;

INNER JOIN keyword selects records that have matching values in both tables.
LEFT JOIN keyword returns all records from the left table (table1), and the
matching records from the right table
RIGHT JOIN keyword returns all records from the right table (table2), and the
matching records from the left table
FULL JOIN or FULL OUTER JOIN keyword returns all records when there is a match in
left or right table records.
Self Join is a regular join, but the table is joined with itself.

UNION operator is used to combine the result-set of two or more SELECT statements
UNION operator selects only distinct values by default

SELECT column_name(s) FROM table1


UNION
SELECT column_name(s) FROM table2;

GROUP BY statement - Gives summary rows for rows that have same values
Used to arrange identical data into groups with the help of some functions
Used with SELECT statement. Placed after the WHERE clause. Placed before ORDER BY.
Placed before HAVING clause.

SELECT column1, function_name(column2)


FROM table_name
WHERE condition
GROUP BY column1, column2
HAVING condition
ORDER BY column1, column2;

SQL EXISTS Operator


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.
SELECT SupplierName
FROM Suppliers
WHERE EXISTS (SELECT ProductName FROM Products WHERE Products.SupplierID =
Suppliers.supplierID AND Price < 20);

ANY and ALL operators allow you to perform a comparison between a single column
value and a range of other values.
ANY operator - returns TRUE if ANY of the subquery values meet the condition
ALL operator - returns TRUE if ALL of the subquery values meet the condition

SELECT ProductName
FROM Products
WHERE ProductID = ANY
(SELECT ProductID
FROM OrderDetails
WHERE Quantity = 10);

SELECT INTO statement copies data from one table into a new table
SELECT * INTO CustomersBackup2017
FROM Customers;
INSERT INTO SELECT statement copies data from one table and inserts it into another
table
Data types in source and target tables must match
INSERT INTO Customers (CustomerName, City, Country)
SELECT SupplierName, City, Country FROM Suppliers;

CASE statement is SQL’s way of handling if/then logic. Two ways of writing
1. Takes a variable called case_value and matches it with some statement_list.
2. executes the statement_list based on search_condition
SELECT CustomerName, Age,
CASE
WHEN Age> 22 THEN 'The Age is greater than 22'
WHEN Age = 21 THEN 'The Age is 21'
ELSE 'The Age is over 30'
END AS QuantityText
FROM Customer;

COALESCE() function lets you return an alternative value if an expression is NULL

SQL Comparison Operators


= Equal to
> Greater than
< Less than
>= Greater than or equal to
<= Less than or equal to
<> Not equal to

Logical Operators
ALL TRUE if all of the subquery values meet the condition
AND TRUE if all the conditions separated by AND is TRUE
ANY TRUE if any of the subquery values meet the condition
BETWEEN TRUE if the operand is within the range of comparisons
EXISTS TRUE if the subquery returns one or more records
IN TRUE if the operand is equal to one of a list of expressions
LIKE TRUE if the operand matches a pattern
NOT Displays a record if the condition(s) is NOT TRUE
OR TRUE if any of the conditions separated by OR is TRUE
SOME TRUE if any of the subquery values meet the condition

CREATE PROCEDURE SelectAllCustomers


AS
SELECT * FROM Customers
GO;

Views in SQL are kind of virtual tables. Has rows and columns as they are in a real
table in the database.
CREATE VIEW MarksView AS
SELECT StudentDetails.NAME, StudentDetails.ADDRESS, StudentMarks.MARKS
FROM StudentDetails, StudentMarks
WHERE StudentDetails.NAME = StudentMarks.NAME

Transactions group a set of tasks into a single execution unit. If any of the tasks
fail, the transaction fails.
Transaction has only two results: success or failure.

BEGIN TRANSACTION transaction_name ; -> It indicates the start point of an explicit


or local transaction.
Set values for the properties of the current transaction, such as the transaction
isolation level and access mode
SET TRANSACTION [ READ WRITE | READ ONLY ];
COMMIT or ROLLBACK command - saves or abort the transactions to the database
SAVEPOINT Command - Creates points within the groups of transactions in which to
ROLLBACK.
Eg: SAVEPOINT SAVEPOINT_NAME;
ROLLBACK TO SAVEPOINT_NAME; - undo a transaction till SAVEPOINT_NAME state
RELEASE SAVEPOINT SAVEPOINT_NAME - Remove a SAVEPOINT that you have created

Properties of Transaction
Atomicity: The outcome of a transaction can either be completely successful or
completely unsuccessful. The whole transaction must be rolled back if one part of
it fails.
Consistency: Transactions maintain integrity restrictions by moving the database
from one valid state to another.
Isolation: Concurrent transactions are isolated from one another, assuring the
accuracy of the data.
Durability: Once a transaction is committed, its modifications remain in effect
even in the event of a system failure.

You might also like