SQL Tutorial1. Get Columns from TableSELECT Syntax:1.1 Get Distinct Columns from one TableSELECT DISTINCT Syntax:2. Where Clause in TableWHERE SyntaxExample2.1. And, Or, NotExampleOperators in The WHERE Clause2.2 Is Null/ Is Not NullIS NULL SyntaxIS NOT NULL SyntaxExample2.3 LikeLIKE SyntaxExample2.4 WildcardsWildcard Characters in MS AccessWildcard Characters in SQL ServerExample2.5 In (a shorthand for multiple OR conditions)IN SyntaxExample2.6 Between AndBETWEEN SyntaxExample2.7 ExistsEXISTS SyntaxExamples3. Having Clause in TableHAVING SyntaxExample4. Order By in TableORDER BY SyntaxExample5. Insert Into-Values for TableINSERT INTO SyntaxExample6. AliasesAlias Column SyntaxAlias Table SyntaxColumns ExampleTables Example7. Update-Set for TableUPDATE SyntaxExample8. Delete from TableDELETE SyntaxExample9. Functions: Top, Min/Max, Count, Avg, Sum from Table9.1 TopSQL Server / MS Access Syntax:MySQL Syntax:Oracle 12 Syntax:Example9.2 Min/MaxMIN() SyntaxMAX() SyntaxExample9.3 COUNT, AVG, SUMCOUNT() SyntaxAVG() SyntaxSUM() SyntaxExample10. Join Two Tables10.1 Inner Join OnINNER JOIN SyntaxExample 10.2 Left Join OnLEFT JOIN SyntaxExample10.3 Right Join OnRIGHT JOIN SyntaxExample10.4 Full Outer Join OnFULL OUTER JOIN SyntaxExample12. Union (All) for Two TablesUNION SyntaxUNION ALL SyntaxExample13. Group By in TableGROUP BY SyntaxExample14. Any, All in Table14.1 AnyANY Syntax14.2 AllALL Syntax With SELECTALL Syntax With WHERE or HAVINGExample15. Select Into New Table or New DatabaseSELECT INTO SyntaxExample16. Insert Into Select for Another TableINSERT INTO SELECT SyntaxExamples17. CaseCASE SyntaxExample18. Null FunctionsSolutions19. Stored ProceduresStored Procedure SyntaxExecute a Stored ProcedureExample20. Comments20.1 Single Line CommentsExample20.2 Multi-line CommentsExample
The SELECT statement is used to select data from a database.
The data returned is stored in a result table, called the result-set.
21SELECT column_1, column_2, ...2FROM table_name1;Here, column1, column2, ... are the field names of the table you want to select data from.
If you want to select all the fields available in the table, use the following syntax:
21# selects all the columns from the "Customers" table:2SELECT * FROM Customers;
The SELECT DISTINCT statement is used to return only distinct (different) values.
Inside a table, a column often contains many duplicate values; and sometimes you only want to list the different (distinct) values.
21SELECT DISTINCT column1, column2, ...2FROM table_name1;
The following SQL statement lists the number of different (distinct) customer countries:
11SELECT COUNT(DISTINCT Country) FROM Customers;Here is the workaround for MS Access:
21SELECT Count(*) AS DistinctCountries2FROM (SELECT DISTINCT Country FROM Customers);
The WHERE clause is used to filter records.
It is used to extract only those records that fulfill a specified condition.
31SELECT column1, column2, ...2FROM table_name13WHERE condition1;Note: The
WHEREclause is not only used inSELECTstatements, it is also used inUPDATE,DELETE, etc.!
21SELECT * FROM Customers2WHERE Country='Mexico';
AND, OR and NOT Operators
The WHERE clause can be combined with AND, OR, and NOT operators.
The AND and OR operators are used to filter records based on more than one condition:
AND operator displays a record if all the conditions separated by AND are TRUE.OR operator displays a record if any of the conditions separated by OR is TRUE.The NOT operator displays a record if the condition(s) is NOT TRUE.
NOT keyword to select all records where City is NOT "Berlin".21SELECT * FROM Customers2WHERE NOT City = 'Berlin';21SELECT * FROM Customers2WHERE CustomerID=1;City column has the value 'Berlin' and the PostalCode column has the value 12209.31SELEC * FROM Customers2WHERE City = 'Berlin'3AND PostalCode = 12209;City column has the value 'Berlin' or 'London'.31SELECT * FROM Customers2WHERE City = 'Berlin'3OR City = 'London';
The following operators can be used in the WHERE clause:
| Operator | Description |
|---|---|
| = | Equal |
| > | Greater than |
| < | Less than |
| >= | Greater than or equal |
| <= | Less than or equal |
| <> | Not equal. Note: In some versions of SQL this operator may be written as != |
| BETWEEN | Between a certain range |
| LIKE | Search for a pattern |
| IN | To specify multiple possible values for a column |
A field with a NULL value is a field with no value.
If a field in a table is optional, it is possible to insert a new record or update a record without adding a value to this field. Then, the field will be saved with a NULL value.
31SELECT column_names2FROM table_name13WHERE column_name IS NULL;31SELECT column_names2FROM table_name13WHERE column_name IS NOT NULL;
The IS NULL operator is used to test for empty values (NULL values).
31SELECT CustomerName, ContactName, Address2FROM Customers3WHERE Address IS NULL;The IS NOT NULL operator is used to test for non-empty values (NOT NULL values).
31SELECT CustomerName, ContactName, Address2FROM Customers3WHERE Address IS NOT NULL;
LIKE Operator:
The LIKE operator is used in a WHERE clause to search for a specified pattern in a column.
There are two wildcards often used in conjunction with the LIKE operator:
Note: MS Access uses an asterisk (*) instead of the percent sign (%), and a question mark (?) instead of the underscore (_).
31SELECT column1, column2, ...2FROM table_name13WHERE columnN LIKE pattern;Tip: You can also combine any number of conditions using
ANDorORoperators.
21SELECT * FROM Customers2WHERE CustomerName LIKE 'a%';21SELECT * FROM Customers2WHERE CustomerName NOT LIKE 'a%';City column contains the letter "a".21SELECT * FROM Customers2WHERE City LIKE '%a%';City column starts with letter "a" and ends with the letter "b".21SELECT * FROM Customers2WHERE City LIKE 'a%b';City column does NOT start with the letter "a".21SELECT * FROM Customers2WHERE City NOT LIKE 'a%';
Wildcard Characters:
A wildcard character is used to substitute one or more characters in a string.
Wildcard characters are used with the LIKE operator. The LIKE operator is used in a WHERE clause to search for a specified pattern in a column.
| 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 |
| # | Represents any single numeric character | 2#5 finds 205, 215, 225, 235, 245, 255, 265, 275, 285, and 295 |
| 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 |
Here are some examples showing different LIKE operators with '%' and '_' wildcards:
| LIKE Operator | Description |
|---|---|
| WHERE CustomerName LIKE 'a%' | Finds any values that starts with "a" |
| WHERE CustomerName LIKE '%a' | Finds any values that ends with "a" |
| WHERE CustomerName LIKE '%or%' | Finds any values that have "or" in any position |
| WHERE CustomerName LIKE '_r%' | Finds any values that have "r" in the second position |
| WHERE CustomerName LIKE 'a__%' | Finds any values that starts with "a" and are at least 3 characters in length |
| WHERE ContactName LIKE 'a%o' | Finds any values that starts with "a" and ends with "o" |
City is an "a".21SELECT * FROM Customers2WHERE City LIKE '_a%';City is an "a" or a "c" or an "s".21SELECT * FROM Customers2WHERE City LIKE '[acs]%';City starts with anything from an "a" to an "f".21SELECT * FROM Customers2WHERE City LIKE '[a-f]%';City is NOT an "a" or a "c" or an "f".21SELECT * FROM Customers2WHERE City LIKE '[!acf]%';
OR conditions)IN Operator:
The IN operator allows you to specify multiple values in a WHERE clause.
The IN operator is a shorthand for multiple OR conditions.
31SELECT column_name(s)2FROM table_name13WHERE column_name IN (value1, value2, ...);or:
31SELECT column_name(s)2FROM table_name13WHERE column_name IN (SELECT STATEMENT);
IN operator to select all the records where Country is either "Norway" or "France".21SELECT * FROM Customers2WHERE Country IN ('Norway','France');IN operator to select all the records where Country is NOT "Norway" and NOT "France".21SELECT * FROM Customers2WHERE Country NOT IN ('Norway', 'France');21SELECT * FROM Customers2WHERE Country IN (SELECT Country FROM Suppliers);
BETWEEN Operator:
The BETWEEN operator selects values within a given range. The values can be numbers, text, or dates.
The BETWEEN operator is inclusive: begin and end values are included.
31SELECT column_name(s)2FROM table_name13WHERE column_name BETWEEN value1 AND value2;
21SELECT * FROM Products2WHERE Price BETWEEN 10 AND 20;NOT BETWEEN:21SELECT * FROM Products2WHERE Price NOT BETWEEN 10 AND 20;31SELECT * FROM Products2WHERE Price BETWEEN 10 AND 203AND CategoryID NOT IN (1,2,3);31SELECT * FROM Products2WHERE ProductName BETWEEN 'Carnarvon Tigers' AND 'Mozzarella di Giovanni'3ORDER BY ProductName;21SELECT * FROM Orders2WHERE OrderDate BETWEEN #07/01/1996# AND #07/31/1996#;or:
21SELECT * FROM Orders2WHERE OrderDate BETWEEN '1996-07-01' AND '1996-07-31';
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.
xxxxxxxxxx1SELECT column_name(s)2FROM table_name13WHERE EXISTS4(SELECT column_name FROM table_name1 WHERE condition1);
31SELECT SupplierName2FROM Suppliers3WHERE EXISTS (SELECT ProductName FROM Products WHERE Products.SupplierID = Suppliers.supplierID AND Price < 20);31SELECT SupplierName2FROM Suppliers3WHERE EXISTS (SELECT ProductName FROM Products WHERE Products.SupplierID = Suppliers.supplierID AND Price = 22);
HAVING Clause:
The HAVING clause was added to SQL because the WHERE keyword cannot be used with aggregate functions.
xxxxxxxxxx61SELECT column_name(s)2FROM table_name13WHERE condition14GROUP BY column_name(s)5HAVING condition16ORDER BY column_name(s);
41SELECT COUNT(CustomerID), Country2FROM Customers3GROUP BY Country4HAVING COUNT(CustomerID) > 5;51SELECT COUNT(CustomerID), Country2FROM Customers3GROUP BY Country4HAVING COUNT(CustomerID) > 55ORDER BY COUNT(CustomerID) DESC;51SELECT Employees.LastName, COUNT(Orders.OrderID) AS NumberOfOrders2FROM (Orders3INNER JOIN Employees ON Orders.EmployeeID = Employees.EmployeeID)4GROUP BY LastName5HAVING COUNT(Orders.OrderID) > 10;61SELECT Employees.LastName, COUNT(Orders.OrderID) AS NumberOfOrders2FROM Orders3INNER JOIN Employees ON Orders.EmployeeID = Employees.EmployeeID4WHERE LastName = 'Davolio' OR LastName = 'Fuller'5GROUP BY LastName6HAVING COUNT(Orders.OrderID) > 25;
ORDER BY Keyword:
The ORDER BY keyword is used to sort the result-set in ascending or descending order.
The ORDER BY keyword sorts the records in ascending order by default. To sort the records in descending order, use the DESC keyword.
31SELECT column1, column2, ...2FROM table_name13ORDER BY column1, column2, ... ASC|DESC;
21SELECT * FROM Customers2ORDER BY Country;21SELECT * FROM Customers2ORDER BY Country DESC;21SELECT * FROM Customers2ORDER BY Country, CustomerName;21SELECT * FROM Customers2ORDER BY Country ASC, CustomerName DESC;
INSERT INTO Statement
The INSERT INTO statement is used to insert new records in a table.
It is possible to write the INSERT INTO statement in two ways:
21INSERT INTO table_name1 (column1, column2, column3, ...)2VALUES (value1, value2, value3, ...);INSERT INTO syntax would be as follows:21INSERT INTO table_name12VALUES (value1, value2, value3, ...);21INSERT INTO Customers (CustomerName, ContactName, Address, City, PostalCode, Country)2VALUES ('Cardinal', 'Tom B. Erichsen', 'Skagen 21', 'Stavanger', '4006', 'Norway');It is also possible to only insert data in specific columns.
The following SQL statement will insert a new record, but only insert data in the "CustomerName", "City", and "Country" columns (CustomerID will be updated automatically):
21INSERT INTO Customers (CustomerName, City, Country)2VALUES ('Cardinal', 'Stavanger', 'Norway');
SQL aliases are used to give a table, or a column in a table, a temporary name.
Aliases are often used to make column names more readable.
An alias only exists for the duration of that query.
An alias is created with the AS keyword.
xxxxxxxxxx1SELECT column_name AS alias_name2FROM table_name1;xxxxxxxxxx1SELECT column_name(s)2FROM table_name1 AS alias_name;
21SELECT CustomerID AS ID, CustomerName AS Customer2FROM Customers;21SELECT CustomerName AS Customer, ContactName AS [Contact Person]2FROM Customers;Note: It requires double quotation marks or square brackets if the alias name contains spaces.
21SELECT CustomerName, Address + ', ' + PostalCode + ' ' + City + ', ' + Country AS Address2FROM Customers;Note: To get the SQL statement above to work in MySQL use the following:
21SELECT CustomerName, CONCAT(Address,', ',PostalCode,', ',City,', ',Country) AS Address2FROM Customers;Note: To get the SQL statement above to work in Oracle use the following:
21SELECT CustomerName, (Address || ', ' || PostalCode || ' ' || City || ', ' || Country) AS Address2FROM Customers;31SELECT o.OrderID, o.OrderDate, c.CustomerName2FROM Customers AS c, Orders AS o3WHERE c.CustomerName='Around the Horn' AND c.CustomerID=o.CustomerID;xxxxxxxxxx31SELECT Orders.OrderID, Orders.OrderDate, Customers.CustomerName2FROM Customers, Orders3WHERE Customers.CustomerName='Around the Horn' AND Customers.CustomerID=Orders.CustomerID;
UPDATE Statement:
The UPDATE statement is used to modify the existing records in a table.
Note: Be careful when updating records in a table! Notice the
WHEREclause in theUPDATEstatement. TheWHEREclause specifies which record(s) that should be updated. If you omit theWHEREclause, all records in the table will be updated!
31UPDATE table_name12SET column1 = value1, column2 = value2, ...3WHERE condition1;
31UPDATE Customers2SET ContactName = 'Alfred Schmidt', City= 'Frankfurt'3WHERE CustomerID = 1; It is the WHERE clause that determines how many records will be updated.
The following SQL statement will update the ContactName to "Juan" for all records where country is "Mexico":
31UPDATE Customers2SET ContactName='Juan'3WHERE Country='Mexico';Note: Be careful when updating records. If you omit the
WHEREclause, ALL records will be updated!
City column of all records in the Customers table.21UPDATE Customers2SET City = 'Oslo';
DELETE Statement:
The DELETE statement is used to delete existing records in a table.
11DELETE FROM table_name1 WHERE condition1;
11DELETE FROM Customers WHERE CustomerName='Alfreds Futterkiste';Note: Be careful when deleting records in a table! Notice the
WHEREclause in theDELETEstatement. TheWHEREclause specifies which record(s) should be deleted. If you omit theWHEREclause, all records in the table will be deleted!
Delete All Records
It is possible to delete all rows in a table without deleting the table. This means that the table structure, attributes, and indexes will be intact:
11DELETE FROM Customers;
SELECT TOP Clause:
The SELECT TOP clause is used to specify the number of records to return.
The SELECT TOP clause is useful on large tables with thousands of records. Returning a large number of records can impact performance.
Note: Not all database systems support the
SELECT TOPclause. MySQL supports theLIMITclause to select a limited number of records, while Oracle usesFETCH FIRST *n* ROWS ONLYandROWNUM.
31SELECT TOP number|percent column_name(s)2FROM table_name13WHERE condition1;41SELECT column_name(s)2FROM table_name13WHERE condition14LIMIT number;41SELECT column_name(s)2FROM table_name13ORDER BY column_name(s)4FETCH FIRST number ROWS ONLY;
11SELECT TOP 3 * FROM Customers;21SELECT * FROM Customers2LIMIT 3;21SELECT * FROM Customers2FETCH FIRST 3 ROWS ONLY;11SELECT TOP 50 PERCENT * FROM Customers;21SELECT * FROM Customers2FETCH FIRST 50 PERCENT ROWS ONLY;
MIN() and MAX() Functions:
The MIN() function returns the smallest value of the selected column.
The MAX() function returns the largest value of the selected column.
31SELECT MIN(column_name)2FROM table_name13WHERE condition1;31SELECT MAX(column_name)2FROM table_name13WHERE condition1;
21SELECT MIN(Price) AS SmallestPrice2FROM Products;21SELECT MAX(Price) AS LargestPrice2FROM Products;
COUNT() function returns the number of rows that matches a specified criterion.31SELECT COUNT(column_name)2FROM table_name13WHERE condition1;AVG() function returns the average value of a numeric column. 31SELECT AVG(column_name)2FROM table_name3WHERE condition;SUM() function returns the total sum of a numeric column. 31SELECT SUM(column_name)2FROM table_name3WHERE condition;
21SELECT COUNT(ProductID)2FROM Products;Note: NULL values are not counted.
21SELECT AVG(Price)2FROM Products;Note: NULL values are ignored.
21SELECT SUM(Quantity)2FROM OrderDetails;Note: NULL values are ignored.
JOIN:
A JOIN clause is used to combine rows from two or more tables, based on a related column between them.
INNER JOIN Keyword:
The INNER JOIN keyword selects records that have matching values in both tables.

41SELECT column_name(s)2FROM table13INNER JOIN table24ON table1.column_name = table2.column_name;31SELECT Orders.OrderID, Customers.CustomerName2FROM Orders3INNER JOIN Customers ON Orders.CustomerID = Customers.CustomerID;Note: The
INNER JOINkeyword selects all rows from both tables as long as there is a match between the columns. If there are records in the "Orders" table that do not have matches in "Customers", these orders will not be shown!
41SELECT Orders.OrderID, Customers.CustomerName, Shippers.ShipperName2FROM ((Orders3INNER JOIN Customers ON Orders.CustomerID = Customers.CustomerID)4INNER JOIN Shippers ON Orders.ShipperID = Shippers.ShipperID);
LEFT JOIN Keyword:
The LEFT JOIN keyword returns all records from the left table (table1), and the matching records from the right table (table2). The result is 0 records from the right side, if there is no match.

41SELECT column_name(s)2FROM table13LEFT JOIN table24ON table1.column_name = table2.column_name;Note: In some databases LEFT JOIN is called LEFT OUTER JOIN.
41SELECT Customers.CustomerName, Orders.OrderID2FROM Customers3LEFT JOIN Orders ON Customers.CustomerID = Orders.CustomerID4ORDER BY Customers.CustomerName;
RIGHT JOIN Keyword:
The RIGHT JOIN keyword returns all records from the right table (table2), and the matching records from the left table (table1). The result is 0 records from the left side, if there is no match.

41SELECT column_name(s)2FROM table13RIGHT JOIN table24ON table1.column_name = table2.column_name;Note: In some databases
RIGHT JOINis calledRIGHT OUTER JOIN.
41SELECT Orders.OrderID, Employees.LastName, Employees.FirstName2FROM Orders3RIGHT JOIN Employees ON Orders.EmployeeID = Employees.EmployeeID4ORDER BY Orders.OrderID;
FULL OUTER JOIN Keyword:
The FULL OUTER JOIN keyword returns all records when there is a match in left (table1) or right (table2) table records.
Tip: FULL OUTER JOIN and FULL JOIN are the same.

51SELECT column_name(s)2FROM table13FULL OUTER JOIN table24ON table1.column_name = table2.column_name5WHERE condition;Note:
FULL OUTER JOINcan potentially return very large result-sets!
41SELECT Customers.CustomerName, Orders.OrderID2FROM Customers3FULL OUTER JOIN Orders ON Customers.CustomerID=Orders.CustomerID4ORDER BY Customers.CustomerName;A selection from the result set may look like this:
| CustomerName | OrderID |
|---|---|
| Null | 10309 |
| Null | 10310 |
| Alfreds Futterkiste | Null |
| Ana Trujillo Emparedados y helados | 10308 |
| Antonio Moreno TaquerÃa | Null |
Note: The
FULL OUTER JOINkeyword returns all matching records from both tables whether the other table matches or not. So, if there are rows in "Customers" that do not have matches in "Orders", or if there are rows in "Orders" that do not have matches in "Customers", those rows will be listed as well.
UNION Operator:
The UNION operator is used to combine the result-set of two or more SELECT statements.
SELECT statement within UNION must have the same number of columnsSELECT statement must also be in the same order31SELECT column_name(s) FROM table12UNION3SELECT column_name(s) FROM table2;The UNION operator selects only distinct values by default. To allow duplicate values, use UNION ALL:
31SELECT column_name(s) FROM table12UNION ALL3SELECT column_name(s) FROM table2;Note: The column names in the result-set are usually equal to the column names in the first
SELECTstatement.
41SELECT City FROM Customers2UNION3SELECT City FROM Suppliers4ORDER BY City;Note: If some customers or suppliers have the same city, each city will only be listed once, because
UNIONselects only distinct values. UseUNION ALLto also select duplicate values!
41SELECT City FROM Customers2UNION ALL3SELECT City FROM Suppliers4ORDER BY City;61SELECT City, Country FROM Customers2WHERE Country='Germany'3UNION4SELECT City, Country FROM Suppliers5WHERE Country='Germany'6ORDER BY City;61SELECT City, Country FROM Customers2WHERE Country='Germany'3UNION ALL4SELECT City, Country FROM Suppliers5WHERE Country='Germany'6ORDER BY City;51SELECT 'Customer' AS Type, ContactName, City, Country2FROM Customers3UNION4SELECT 'Supplier', ContactName, City, Country5FROM Suppliers;Notice the "AS Type" above - it is an alias. SQL Aliases are used to give a table or a column a temporary name. An alias only exists for the duration of the query. So, here we have created a temporary column named "Type", that list whether the contact person is a "Customer" or a "Supplier".
GROUP BY Statement:
The GROUP BY statement groups rows that have the same values into summary rows, like "find the number of customers in each country".
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.
31SELECT column_name(s)2FROM table_name3GROUP BY column_name(s)
31SELECT COUNT(CustomerID), Country2FROM Customers3GROUP BY Country;41SELECT COUNT(CustomerID), Country2FROM Customers3GROUP BY Country4ORDER BY COUNT(CustomerID) DESC;31SELECT Shippers.ShipperName, COUNT(Orders.OrderID) AS NumberOfOrders FROM Orders2LEFT JOIN Shippers ON Orders.ShipperID = Shippers.ShipperID3GROUP BY ShipperName;
ANY and ALL Operators:
The ANY and ALL operators allow you to perform a comparison between a single column value and a range of other values.
The ANY operator:
ANY means that the condition will be true if the operation is true for any of the values in the range.
xxxxxxxxxx1SELECT column_name(s)2FROM table_name13WHERE column_name operator ANY4 (SELECT column_name5 FROM table_name16 WHERE condition1);Note: The operator must be a standard comparison operator (=, <>, !=, >, >=, <, or <=).
The ALL operator:
SELECT, WHERE and HAVING statementsALL means that the condition will be true only if the operation is true for all values in the range.
xxxxxxxxxx1SELECT ALL column_name(s)2FROM table_name13WHERE condition1;xxxxxxxxxx1SELECT column_name(s)2FROM table_name13WHERE column_name operator ALL4 (SELECT column_name5 FROM table_name16 WHERE condition1);Note: The operator must be a standard comparison operator (=, <>, !=, >, >=, <, or <=).
61SELECT ProductName2FROM Products3WHERE ProductID = ANY4 (SELECT ProductID5 FROM OrderDetails6 WHERE Quantity = 10);31SELECT ALL ProductName2FROM Products3WHERE TRUE;61SELECT ProductName2FROM Products3WHERE ProductID = ALL4 (SELECT ProductID5 FROM OrderDetails6 WHERE Quantity = 10);
SELECT INTO Statement:
The SELECT INTO statement copies data from one table into a new table.
Copy all columns into a new table:
41SELECT *2INTO newtable [IN externaldb]3FROM oldtable4WHERE condition;Copy only some columns into a new table:
41SELECT column1, column2, column3, ...2INTO newtable [IN externaldb]3FROM oldtable4WHERE condition;
21SELECT * INTO CustomersBackup20172FROM Customers;IN clause to copy the table into a new table in another database:21SELECT * INTO CustomersBackup2017 IN 'Backup.mdb'2FROM Customers;21SELECT CustomerName, ContactName INTO CustomersBackup20172FROM Customers;31SELECT * INTO CustomersGermany2FROM Customers3WHERE Country = 'Germany';41SELECT Customers.CustomerName, Orders.OrderID2INTO CustomersOrderBackup20173FROM Customers4LEFT JOIN Orders ON Customers.CustomerID = Orders.CustomerID;Tip:
SELECT INTOcan also be used to create a new, empty table using the schema of another. Just add aWHEREclause that causes the query to return no data:
31SELECT * INTO newtable2FROM oldtable3WHERE 1 = 0;
INSERT INTO SELECT Statement:
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.
Note: The existing records in the target table are unaffected.
Copy all columns from one table to another table:
xxxxxxxxxx1INSERT INTO table22SELECT * FROM table13WHERE condition1;Copy only some columns from one table into another table:
xxxxxxxxxx1INSERT INTO table2 (column1, column2, column3, ...)2SELECT column1, column2, column3, ...3FROM table14WHERE condition1;
21INSERT INTO Customers (CustomerName, City, Country)2SELECT SupplierName, City, Country FROM Suppliers;21INSERT INTO Customers (CustomerName, ContactName, Address, City, PostalCode, Country)2SELECT SupplierName, ContactName, Address, City, PostalCode, Country FROM Suppliers;31INSERT INTO Customers (CustomerName, City, Country)2SELECT SupplierName, City, Country FROM Suppliers3WHERE Country='Germany';
CASE Expression:
The CASE expression 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.
61CASE2 WHEN condition1 THEN result13 WHEN condition2 THEN result24 WHEN conditionN THEN resultN5 ELSE result6END;
71SELECT OrderID, Quantity,2CASE3 WHEN Quantity > 30 THEN 'The quantity is greater than 30'4 WHEN Quantity = 30 THEN 'The quantity is 30'5 ELSE 'The quantity is under 30'6END AS QuantityText7FROM OrderDetails;71SELECT CustomerName, City, Country2FROM Customers3ORDER BY4(CASE5 WHEN City IS NULL THEN Country6 ELSE City7END);
IFNULL(), ISNULL(), COALESCE(), and NVL() Functions:
Look at the following "Products" table:
| P_Id | ProductName | UnitPrice | UnitsInStock | UnitsOnOrder |
|---|---|---|---|---|
| 1 | Jarlsberg | 10.45 | 16 | 15 |
| 2 | Mascarpone | 32.56 | 23 | |
| 3 | Gorgonzola | 15.67 | 9 | 20 |
Suppose that the "UnitsOnOrder" column is optional, and may contain NULL values.
Look at the following SELECT statement:
21SELECT ProductName, UnitPrice * (UnitsInStock + UnitsOnOrder)2FROM Products;In the example above, if any of the "UnitsOnOrder" values are NULL, the result will be NULL.
MySQL
The MySQL IFNULL() function lets you return an alternative value if an expression is NULL:
21SELECT ProductName, UnitPrice * (UnitsInStock + IFNULL(UnitsOnOrder, 0))2FROM Products;or we can use the COALESCE() function, like this:
21SELECT ProductName, UnitPrice * (UnitsInStock + COALESCE(UnitsOnOrder, 0))2FROM Products;SQL Server
The SQL Server ISNULL() function lets you return an alternative value when an expression is NULL:
21SELECT ProductName, UnitPrice * (UnitsInStock + ISNULL(UnitsOnOrder, 0))2FROM Products;or we can use the COALESCE() function, like this:
21SELECT ProductName, UnitPrice * (UnitsInStock + COALESCE(UnitsOnOrder, 0))2FROM Products;MS Access
The MS Access IsNull() function returns TRUE (-1) if the expression is a null value, otherwise FALSE (0):
21SELECT ProductName, UnitPrice * (UnitsInStock + IIF(IsNull(UnitsOnOrder), 0, UnitsOnOrder))2FROM Products;Oracle
The Oracle NVL() function achieves the same result:
21SELECT ProductName, UnitPrice * (UnitsInStock + NVL(UnitsOnOrder, 0))2FROM Products;or we can use the COALESCE() function, like this:
21SELECT ProductName, UnitPrice * (UnitsInStock + COALESCE(UnitsOnOrder, 0))2FROM Products;
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.
41CREATE PROCEDURE procedure_name2AS3sql_statement4GO;11EXEC procedure_name;
41CREATE PROCEDURE SelectAllCustomers2AS3SELECT * FROM Customers4GO;Execute the stored procedure above as follows:
11EXEC SelectAllCustomers;41CREATE PROCEDURE SelectAllCustomers @City nvarchar(30)2AS3SELECT * FROM Customers WHERE City = @City4GO;Execute the stored procedure above as follows:
11EXEC SelectAllCustomers @City = 'London';Setting up multiple parameters is very easy. Just list each parameter and the data type separated by a comma as shown below.
The following SQL statement creates a stored procedure that selects Customers from a particular City with a particular PostalCode from the "Customers" table:
41CREATE PROCEDURE SelectAllCustomers @City nvarchar(30), @PostalCode nvarchar(10)2AS3SELECT * FROM Customers WHERE City = @City AND PostalCode = @PostalCode4GO;Execute the stored procedure above as follows:
xxxxxxxxxx11EXEC SelectAllCustomers @City = 'London', @PostalCode = 'WA1 1DP';
Comments:
Comments are used to explain sections of SQL statements, or to prevent execution of SQL statements.
Single line comments start with --.
Any text between -- and the end of the line will be ignored (will not be executed).
21--Select all:2SELECT * FROM Customers;11SELECT * FROM Customers -- WHERE City='Berlin';
Multi-line comments start with /* and end with */.
Any text between /* and */ will be ignored.
xxxxxxxxxx41/*Select all the columns2of all the records3in the Customers table:*/4SELECT * FROM Customers;To ignore just a part of a statement, also use the /* */ comment.
The following example uses a comment to ignore part of a line:
11SELECT CustomerName, /*City,*/ Country FROM Customers;51SELECT * FROM Customers WHERE (CustomerName LIKE 'L%'2OR CustomerName LIKE 'R%' /*OR CustomerName LIKE 'S%'3OR CustomerName LIKE 'T%'*/ OR CustomerName LIKE 'W%')4AND Country='USA'5ORDER BY CustomerName;