SELECT INTO: copies data from one table into a new table
Syntax
SELECT *
INTO newtable [IN externaldb]
FROM oldtable
WHERE condition;
SELECT column1, column2, column3, ...
INTO newtable [IN externaldb]
FROM oldtable
WHERE condition;
Example (1): creates a backup copy of Customers
SELECT * INTO CustomersBackup2017
FROM Customers;
Example (2): copy the table into a new table in another database
SELECT * INTO CustomersBackup2017 IN 'Backup.mdb'
FROM Customers;
Example (3): copies only a few columns into a new table
SELECT CustomerName, ContactName INTO CustomersBackup2017
FROM Customers;
Example (4): copies data from more than one table into a new table
SELECT Customers.CustomerName, Orders.OrderID
INTO CustomersOrderBackup2017
FROM Customers
LEFT JOIN Orders ON Customers.CustomerID = Orders.CustomerID;
Example (5): creates a new empty table
SELECT * INTO newtable
FROM oldtable
WHERE 1 = 0;
INSERT INTO SELECT statement
Syntax
INSERT INTO table2
SELECT * FROM table1
WHERE condition;
INSERT INTO table2 (column1, column2, column3, ...)
SELECT column1, column2, column3, ...
FROM table1
WHERE condition;
CASE Expression
Syntax
CASE
WHEN condition1 THEN result1
WHEN condition2 THEN result2
WHEN conditionN THEN resultN
ELSE result
END;
Example 1: goes through conditions and returns a value when the first condition is met
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;
Example 2: order the customers by City but if City is null, order by Country
SELECT CustomerName, City, Country
FROM Customers
ORDER BY
(CASE
WHEN City IS NULL THEN Country
ELSE City
END);
IFNULL(): lets you return an alternative value if an expression is null
SELECT ProductName, UnitPrice * (UnitsInStock + ifNULL(UnitsOnOrder, 0))
FROM Products;
COALESCE(): does the same job as above
SELECT ProductName, UnitPrice * (UnitsInStock + COALESCE(UnitsOnOrder, 0))
FROM Products;
Stored procedure: a prepared SQL code that you can save, so the code can be reused
Stored procedure syntax
CREATE PROCEDURE procedure_name
AS
sql_statement
GO;
Execute a stored procedure
EXEC procedure_name;
Example 1: Procedure with one parameter
CREATE PROCEDURE SelectAllCustomers @City nvarchar(30)
AS
SELECT * FROM Customers WHERE City = @City
GO;
EXEC SelectAllCustomers @City = 'London';
Example 2: Procedure with multiple parameters
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';
This post is based on W3School's articles about SQL.