You are on page 1of 10

SQL

A table consists of fields and Records.


Columns and Rows

Some of The Most Important SQL Commands


SELECT - extracts data from a database
UPDATE - updates data in a database
DELETE - deletes data from a database
INSERT INTO - inserts new data into a database
CREATE DATABASE - creates a new database
ALTER DATABASE - modifies a database
CREATE TABLE - creates a new table
ALTER TABLE - modifies a table
DROP TABLE - deletes a table
CREATE INDEX - creates an index (search key)
DROP INDEX - deletes an index

The WHERE clause is not only used in SELECT statements, it is also used in UPDATE,
DELETE, etc.

select * from customer where NOT city = "Berlin"


# selecting all the record of the customer base from every city except berlin

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

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


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

If you are adding values for all the columns of the table
->INSERT INTO table_name
VALUES (value1, value2, value3, ...);

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

UPDATE table_name
SET column1 = value1, column2 = value2, ...
WHERE condition;

eg - update Customers (Table Name)


set city(variable name) = "oslo", customer_Pref = "Tall"
where country = "Norway"

DELETE FROM table_name WHERE condition;

Select all records where the first letter of the City is an "a" or a "c" or an "s".
SELECT * FROM Customers
WHERE City LIKE '[acs]%';

Select all records where the first letter of the City starts with anything from an
"a" to an "f".
SELECT * FROM Customers
WHERE City LIKE '[a-f]%';
Select all records where the first letter of the City is NOT an "a" or a "c" or an
"f".
SELECT * FROM Customers
WHERE City LIKE '[^acf]%';

SELECT * FROM Customers


where country IN ('Norway', 'France');

SELECT * FROM Customers


WHERE Country NOT IN ('Norway', 'France');

Wildcard Characters in SQL Server


Symbol Description Example
% Represents zero or more characters bl% finds bl, black,
blue, and blob
_ Represents a single character h_t finds hot, hat, and
hit
[] Represents any single character within the brackets h[oa]t finds hot
and hat, but not hit
^ Represents any character not in the brackets h[^oa]t finds
hit, but not hot and hat
- Represents any single character within the specified range c[a-b]t finds cat
and cbt

Join clause
SELECT Orders.OrderID, Customers.CustomerName, Orders.OrderDate
FROM Orders
INNER JOIN Customers ON Orders.CustomerID=Customers.CustomerID;

SELECT Orders.OrderID, Customers.CustomerName, Shippers.ShipperName


FROM ((Orders
INNER JOIN Customers ON Orders.CustomerID = Customers.CustomerID)
INNER JOIN Shippers ON Orders.ShipperID = Shippers.ShipperID);

Using Self join -


You use a self join when a table references data in itself. E.g., an Employee table
may have a SupervisorID column that points to the employee that is the boss of the
current employee.

SELECT column_name(s)
FROM table1 T1, table1 T2
WHERE condition;

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;

select e1.EmployeeID,
e1.FirstName,
e1.LastName,
e1.SupervisorID,
e2.FirstName as SupervisorFirstName,
e2.LastName as SupervisorLastName
from Employee e1
left outer join Employee e2 on e1.SupervisorID = e2.EmployeeID

The UNION operator is used to combine the result-set of two or more SELECT
statements.

Every SELECT statement within UNION must have the same number of columns
The columns must also have similar data types
The columns in every SELECT statement must also be in the same order

SELECT City FROM Customers


UNION
SELECT City FROM Suppliers
ORDER BY City;

SELECT COUNT(CustomerID), Country


FROM Customers
GROUP BY Country;

SELECT COUNT(CustomerID), Country


FROM Customers
GROUP BY Country
ORDER BY COUNT(CustomerID) DESC;

The HAVING clause was added to SQL because the WHERE keyword cannot be used with
aggregate functions.

SELECT column_name(s)
FROM table_name
WHERE condition
GROUP BY column_name(s)
HAVING condition
ORDER BY column_name(s);

SELECT COUNT(CustomerID), Country


FROM Customers
GROUP BY Country
HAVING COUNT(CustomerID) > 5;

SELECT Employees.LastName, COUNT(Orders.OrderID) AS NumberOfOrders


FROM (Orders
INNER JOIN Employees ON Orders.EmployeeID = Employees.EmployeeID)
GROUP BY LastName
HAVING COUNT(Orders.OrderID) > 10;

SELECT Employees.LastName, COUNT(Orders.OrderID) AS NumberOfOrders


FROM Orders
INNER JOIN Employees ON Orders.EmployeeID = Employees.EmployeeID
WHERE LastName = 'Davolio' OR LastName = 'Fuller'
GROUP BY LastName
HAVING COUNT(Orders.OrderID) > 25;

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 = 22);

The ANY operator:


returns a boolean value as a result
returns TRUE if ANY of the subquery values meet the condition

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

The ALL operator:


returns a boolean value as a result
returns TRUE if ALL of the subquery values meet the condition
is used with SELECT, WHERE and HAVING statements
ALL means that the condition will be true only if the operation is true for all
values in the range.

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

##############################################################

New

The SELECT INTO statement copies data from one table into a new table.

SELECT *
INTO newtable [IN externaldb]
FROM oldtable
WHERE condition;

SELECT column1, column2, column3, ...


INTO newtable [IN externaldb]
FROM oldtable
WHERE condition;

The INSERT INTO SELECT statement copies data from one table and inserts it into
another table.
The INSERT INTO SELECT statement requires that the data types in source and target
tables match.

INSERT INTO table2


SELECT * FROM table1
WHERE condition;

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


SELECT column1, column2, column3, ...
FROM table1
WHERE condition;

The SQL CASE Statement


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 is true, it
will stop reading and return the result. If no conditions are true, it returns the
value in the ELSE clause.
If there is no ELSE part and no conditions are true, it returns NULL.

CASE
WHEN condition1 THEN result1
WHEN condition2 THEN result2
WHEN conditionN THEN resultN
ELSE result
END;

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 OrderDetails;

The following SQL will order the customers by City. However, if City is NULL, then
order by Country:
SELECT CustomerName, City, Country
FROM Customers
ORDER BY
(CASE
WHEN City IS NULL THEN Country
ELSE City
END);

The MySQL IFNULL() function lets you return an alternative value if an expression
is NULL:
The SQL Server ISNULL() function lets you return an alternative value when an
expression is NULL:

SELECT ProductName, UnitPrice * (UnitsInStock + ISNULL(UnitsOnOrder, 0))


FROM Products;

What is a Stored Procedure?


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 a 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 value(s) that is passed.
Stored Procedure Syntax
CREATE PROCEDURE procedure_name
AS
sql_statement
GO;
Execute a Stored Procedure
EXEC procedure_name;

Eg-
CREATE PROCEDURE SelectAllCustomers
AS
SELECT * FROM Customers
GO;

Eg-
CREATE PROCEDURE SelectAllCustomers @City nvarchar(30)
AS
SELECT * FROM Customers WHERE City = @City
GO;
EXEC SelectAllCustomers @City = 'London';

Eg-
CREATE PROCEDURE SelectAllCustomers @City nvarchar(30), @PostalCode nvarchar(10)
AS
SELECT * FROM Customers WHERE City = @City AND PostalCode = @PostalCode
GO;

EXEC SelectAllCustomers @City = 'London', @PostalCode = 'WA1 1DP';

Comments
Single line comments start with --.
Any text between -- and the end of the line will be ignored (will not be executed).

Multi-line comments start with /* and end with */.


Any text between /* and */ will be ignored.

Important page - https://www.w3schools.com/sql/sql_operators.asp

Database
The CREATE DATABASE statement is used to create a new SQL database.
CREATE DATABASE databasename;
CREATE DATABASE testDB;

The DROP DATABASE statement is used to drop an existing SQL database.


DROP DATABASE databasename;

The BACKUP DATABASE statement is used in SQL Server to create a full back up of an
existing SQL database.

BACKUP DATABASE databasename


TO DISK = 'filepath';
The SQL BACKUP WITH DIFFERENTIAL Statement
A differential back up only backs up the parts of the database that have changed
since the last full database backup.

Syntax
BACKUP DATABASE databasename
TO DISK = 'filepath'
WITH DIFFERENTIAL;

The CREATE TABLE statement is used to create a new table in a database.

CREATE TABLE PERSONS


(
PersonID int,
LastName varchar(255),
FirstName varchar(255),
Address varchar(255),
City varchar(255)
);

A copy of an existing table can also be created using CREATE TABLE.

CREATE TABLE new_table_name AS


SELECT column1, column2,...
FROM existing_table_name
WHERE ....;

CREATE TABLE TestTable AS


SELECT customername, contactname
FROM customers;

DROP TABLE table_name;

The TRUNCATE TABLE statement is used to delete the data inside a table, but not the
table itself.
TRUNCATE TABLE table_name;

The ALTER TABLE statement is used to add, delete, or modify columns in an existing
table.
The ALTER TABLE statement is also used to add and drop various constraints on an
existing table.

ALTER TABLE Customers


ADD Email varchar(255);

ALTER TABLE Customers


DROP COLUMN Email;

ALTER TABLE table_name


MODIFY COLUMN column_name datatype;
SQL Create Constraints
Constraints can be specified when the table is created with the CREATE TABLE
statement, or after the table is created with the ALTER TABLE statement.

CREATE TABLE table_name (


column1 datatype constraint,
column2 datatype constraint,
column3 datatype constraint,
....
);

ALTER TABLE Persons


MODIFY Age int NOT NULL;

SQL Constraints
SQL constraints are used to specify rules for the data in a table.

Constraints are used to limit the type of data that can go into a table. This
ensures the accuracy and reliability of the data in the table. If there is any
violation between the constraint and the data action, the action is aborted.

Constraints can be column level or table level. Column level constraints apply to a
column, and table level constraints apply to the whole table.

The following constraints are commonly used in SQL:

NOT NULL - Ensures that a column cannot have a NULL value


UNIQUE - Ensures that all values in a column are different
PRIMARY KEY - A combination of a NOT NULL and UNIQUE. Uniquely identifies each row
in a table
FOREIGN KEY - Prevents actions that would destroy links between tables
CHECK - Ensures that the values in a column satisfies a specific condition
DEFAULT - Sets a default value for a column if no value is specified
CREATE INDEX - Used to create and retrieve data from the database very quickly

The FOREIGN KEY constraint is used to prevent actions that would destroy links
between tables.
A FOREIGN KEY is a field (or collection of fields) in one table, that refers to the
PRIMARY KEY in another table.
The table with the foreign key is called the child table, and the table with the
primary key is called the referenced or parent table.

The CHECK constraint is used to limit the value range that can be placed in a
column.
CREATE TABLE Persons (
ID int NOT NULL,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Age int,
CHECK (Age>=18)
);

The DEFAULT constraint is used to set a default value for a column.


CREATE TABLE Persons (
ID int NOT NULL,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Age int,
City varchar(255) DEFAULT 'Sandnes'
);

The CREATE INDEX statement is used to create indexes in tables.

Indexes are used to retrieve data from the database more quickly than otherwise.
The users cannot see the indexes, they are just used to speed up searches/queries.

DUPLICATES VALUES ARE ALLOWED


CREATE INDEX index_name
ON table_name (column1, column2, ...);

DUPLICATES VALUES NOT ALLOWED


CREATE UNIQUE INDEX index_name
ON table_name (column1, column2, ...);

The DROP INDEX statement is used to delete an index in a table.

AUTO INCREMENT Field


Auto-increment allows a unique number to be generated automatically when a new
record is inserted into a table.
Often this is the primary key field that we would like to be created automatically
every time a new record is inserted.

CREATE TABLE Persons (


Personid int NOT NULL AUTO_INCREMENT,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Age int,
PRIMARY KEY (Personid)
);

To let the AUTO_INCREMENT sequence start with another value, use the following SQL
statement:

ALTER TABLE Persons AUTO_INCREMENT=100;

INSERT INTO Persons (FirstName,LastName)


VALUES ('Lars','Monsen');
The SQL statement above would insert a new record into the "Persons" table. The
"Personid" column would be assigned a unique value. The "FirstName" column would be
set to "Lars" and the "LastName" column would be set to "Monsen".

SQL CREATE VIEW Statement


In SQL, a view is a virtual table based on the result-set of an SQL statement.
A view contains rows and columns, just like a real table. The fields in a view are
fields from one or more real tables in the database.
You can add SQL statements and functions to a view and present the data as if the
data were coming from one single table.
A view is created with the CREATE VIEW statement.
CREATE VIEW view_name AS
SELECT column1, column2, ...
FROM table_name
WHERE condition;

CREATE VIEW vw_combined AS


SELECT *
FROM TABLE1 t1
JOIN TABLE2 t2 ON t2.col = t1.col

A view can be updated with the CREATE OR REPLACE VIEW statement.

CREATE OR REPLACE VIEW [Brazil Customers] AS


SELECT CustomerName, ContactName, City
FROM Customers
WHERE Country = 'Brazil';

You might also like