Introduction To SQL Part 1
Introduction To SQL Part 1
What is SQL?
SQL stands for Structured Query Language SQL lets you access and manipulate databases SQL is an ANSI (American National Standards Institute) standard
SQL can execute queries against a database SQL can retrieve data from a database SQL can insert records in a database SQL can update records in a database SQL can delete records from a database SQL can create new databases SQL can create new tables in a database SQL can create stored procedures in a database SQL can create views in a database SQL can set permissions on tables, procedures, and views
An RDBMS database program (i.e. MS Access, SQL Server, MySQL) To use a server-side scripting language, like PHP or ASP To use SQL to get the data you want To use HTML / CSS
RDBMS
RDBMS stands for Relational Database Management System. RDBMS is the basis for SQL, and for all modern database systems such as MS SQL Server, IBM DB2, Oracle, MySQL, and Microsoft Access. The data in RDBMS is stored in database objects called tables. A table is a collection of related data entries and it consists of columns and rows.
SQL Syntax
Database Tables
A database most often contains one or more tables. Each table is identified by a name (e.g. "Customers" or "Orders"). Tables contain records (rows) with data. In this tutorial we will use the well-known Northwind sample database (included in MS Access and MS SQL Server). Below is a selection from the "Customers" table: CustomerID CustomerName ContactName Address 1 Alfreds Futterkiste Maria Anders Obere Str. 57 2 3 4 5 Ana Trujillo Emparedados y helados Antonio Moreno Taquera Around the Horn Berglunds snabbkp Ana Trujillo Antonio Moreno Thomas Hardy Christina Berglund Avda. de la Constitucin 2222 Mataderos 2312 120 Hanover Sq. City Berlin PostalCode Country 12209 Germany Mexico Mexico
Berguvsvgen 8 Lule
The table above contains five records (one for each customer) and seven columns (CustomerID, CustomerName, ContactName, Address, City, PostalCode, and Country).
SQL Statements
Most of the actions you need to perform on a database are done with SQL statements. The following SQL statement selects all the records in the "Customers" table:
Example
SELECT * FROM Customers;
and
SELECT * FROM table_name;
Demo Database
In this tutorial we will use the well-known Northwind sample database. Below is a selection from the "Customers" table:
CustomerID 1 CustomerName Alfreds Futterkiste Ana Trujillo Emparedados y helados Antonio Moreno Taquera ContactName Maria Anders Address Obere Str. 57 City Berlin PostalCode Country 12209 Germany
Ana Trujillo
Mexico
Antonio Moreno
Mataderos 2312
Mexico
4 5
UK Sweden
Example
SELECT CustomerName,City FROM Customers;
SELECT * Example
The following SQL statement selects all the columns from the "Customers" table:
Example
SELECT * FROM Customers;
Demo Database
In this tutorial we will use the well-known Northwind sample database. Below is a selection from the "Customers" table:
CustomerID 1 CustomerName Alfreds Futterkiste Ana Trujillo Emparedados y helados Antonio Moreno Taquera Around the Horn Berglunds snabbkp ContactName Maria Anders Address Obere Str. 57 City Berlin PostalCode Country 12209 Germany
Ana Trujillo
Avda. de la Mxico 05021 Constitucin 2222 D.F. Mxico 05023 D.F. London WA1 1DP Lule S-958 22
Mexico
3 4 5
Antonio Moreno
Mataderos 2312
Mexico UK Sweden
Example
SELECT DISTINCT City FROM Customers;
Demo Database
In this tutorial we will use the well-known Northwind sample database. Below is a selection from the "Customers" table:
CustomerID 1
CustomerName Alfreds Futterkiste Ana Trujillo Emparedados y helados Antonio Moreno Taquera Around the Horn Berglunds snabbkp
City Berlin
Ana Trujillo
Avda. de la Mxico 05021 Constitucin 2222 D.F. Mxico 05023 D.F. London WA1 1DP Lule S-958 22
Mexico
3 4 5
Antonio Moreno
Mataderos 2312
Mexico UK Sweden
Example
SELECT * FROM Customers WHERE Country='Mexico';
Example
SELECT * FROM Customers WHERE CustomerID=1;
Demo Database
In this tutorial we will use the well-known Northwind sample database. Below is a selection from the "Customers" table: CustomerID CustomerName ContactName Address 1 Alfreds Futterkiste Maria Anders Obere Str. 57 2 3 4 5 Ana Trujillo Emparedados y helados Antonio Moreno Taquera Around the Horn Berglunds snabbkp Ana Trujillo Antonio Moreno Thomas Hardy Christina Berglund Avda. de la Constitucin 2222 Mataderos 2312 120 Hanover Sq. City Berlin PostalCode Country 12209 Germany Mexico Mexico
Berguvsvgen 8 Lule
Example
SELECT * FROM Customers WHERE Country='Germany' AND City='Berlin';
OR Operator Example
The following SQL statement selects all customers from the city "Berlin" OR "Mnchen", in the "Customers" table:
Example
Example
SELECT * FROM Customers WHERE Country='Germany' AND (City='Berlin' OR City='Mnchen');
Demo Database
In this tutorial we will use the well-known Northwind sample database. Below is a selection from the "Customers" table:
CustomerID 1 CustomerName Alfreds Futterkiste Ana Trujillo Emparedados y helados Antonio Moreno Taquera Around the Horn Berglunds snabbkp ContactName Maria Anders Address Obere Str. 57 City Berlin PostalCode Country 12209 Germany
Ana Trujillo
Avda. de la Mxico 05021 Constitucin 2222 D.F. Mxico 05023 D.F. London WA1 1DP Lule S-958 22
Mexico
3 4 5
Antonio Moreno
Mataderos 2312
Mexico UK Sweden
ORDER BY Example
The following SQL statement selects all customers from the "Customers" table, sorted by the "Country" column:
Example
SELECT * FROM Customers ORDER BY Country;
Example
SELECT * FROM Customers ORDER BY Country DESC;
Example
SELECT * FROM Customers ORDER BY Country,CustomerName;
It is possible to write the INSERT INTO statement in two forms. The first form does not specify the column names where the data will be inserted, only their values:
INSERT INTO table_name VALUES (value1,value2,value3,...);
The second form specifies both the column names and the values to be inserted:
Demo Database
In this tutorial we will use the well-known Northwind sample database. Below is a selection from the "Customers" table:
CustomerID 87 CustomerName Wartian Herkku Wellington Importadora ContactName Pirkko Koskitalo Address Torikatu 38 City Oulu PostalCode Country 90110 Finland
88
Paula Parente Rua do Mercado, 12 305 - 14th Ave. S. Suite 3B Keskuskatu 45 ul. Filtrowa 68
89
Seattle 98128
USA
90 91
Finland Poland
INSERT INTO Customers (CustomerName, ContactName, Address, City, PostalCode, Country) VALUES ('Cardinal','Tom B. Erichsen','Skagen 21','Stavanger','4006','Norway');
The selection from the "Customers" table will now look like this:
CustomerID 87 CustomerName Wartian Herkku Wellington Importadora White Clover Markets Wilman Kala Wolski Cardinal ContactName Pirkko Koskitalo Address Torikatu 38 City Oulu PostalCode Country 90110 Finland
88
Paula Parente Rua do Mercado, 12 Resende 08737-363 Brazil 305 - 14th Ave. S. Suite 3B Keskuskatu 45 ul. Filtrowa 68 Skagen 21
89
Seattle
98128
USA
90 91 92
Helsinki Walla
21240 01-012
Stavanger 4006
Did you notice that we did not insert any number into the CustomerID field? The CustomerID column is an AutoNumber field and is automatically updated with a unique number for each record in the table. AutoNumber is a type of data used in Microsoft Access tables to generate an automatically incremented numeric counter. The default AutoNumber type has a start value of 1 and an increment of 1.
The following SQL statement will insert a new row, but only insert data in the "CustomerName", "City", and "Country" columns (and the CustomerID field will of course also be updated automatically):
INSERT INTO Customers (CustomerName, City, Country) VALUES ('Cardinal', 'Stavanger', 'Norway');
The selection from the "Customers" table will now look like this:
CustomerID 87 CustomerName Wartian Herkku Wellington Importadora White Clover Markets Wilman Kala Wolski Cardinal ContactName Pirkko Koskitalo Address Torikatu 38 City Oulu PostalCode Country 90110 Finland
88
Paula Parente Rua do Mercado, 12 Resende 08737-363 Brazil 305 - 14th Ave. S. Suite 3B Keskuskatu 45 ul. Filtrowa 68
89
Seattle
98128
USA
90 91 92
21240 01-012
Notice the WHERE clause in the SQL UPDATE statement! The WHERE clause specifies which record or records that should be updated. If you omit the WHERE clause, all records will be updated!
Demo Database
In this tutorial we will use the well-known Northwind sample database. Below is a selection from the "Customers" table:
CustomerID 1 CustomerName Alfreds Futterkiste Ana Trujillo Emparedados y helados Antonio Moreno Taquera Around the Horn Berglunds snabbkp ContactName Maria Anders Address Obere Str. 57 City Berlin PostalCode Country 12209 Germany
Ana Trujillo
Avda. de la Mxico 05021 Constitucin 2222 D.F. Mxico 05023 D.F. London WA1 1DP Lule S-958 22
Mexico
3 4 5
Antonio Moreno
Mataderos 2312
Mexico UK Sweden
Assume we wish to update the customer "Alfreds Futterkiste" with a new contact person and city. We use the following SQL statement:
UPDATE Customers SET ContactName='Alfred Schmidt', City='Hamburg' WHERE CustomerName='Alfreds Futterkiste';
The selection from the "Customers" table will now look like this:
CustomerID 1 CustomerName Alfreds Futterkiste Ana Trujillo Emparedados y helados Antonio Moreno Taquera Around the Horn Berglunds snabbkp ContactName Address City PostalCode Country Germany
Hamburg 12209
Ana Trujillo
05021
Mexico
3 4 5
Antonio Moreno
Mataderos 2312
Mexico UK Sweden
Update Warning!
Be careful when updating records. If we had omitted the WHERE clause in the example above, like this:
UPDATE Customers SET ContactName='Alfred Schmidt', City='Hamburg';
Alfreds Futterkiste
Alfred Schmidt
Hamburg 12209
Germany
Ana Trujillo Alfred Emparedados y helados Schmidt Antonio Moreno Taquera Around the Horn Alfred Schmidt Alfred Schmidt Alfred Schmidt
Hamburg 05021
Mexico
Hamburg 05023
Mexico
UK
Berglunds snabbkp
Berguvsvgen 8
Hamburg S-958 22
Sweden
Notice the WHERE clause in the SQL DELETE statement! The WHERE clause specifies which record or records that should be deleted. If you omit the WHERE clause, all records will be deleted!
Demo Database
In this tutorial we will use the well-known Northwind sample database. Below is a selection from the "Customers" table:
CustomerID 1 CustomerName Alfreds Futterkiste Ana Trujillo Emparedados y helados Antonio Moreno Taquera Around the Horn Berglunds snabbkp ContactName Maria Anders Address Obere Str. 57 City Berlin PostalCode Country 12209 Germany
Ana Trujillo
Avda. de la Mxico 05021 Constitucin 2222 D.F. Mxico 05023 D.F. London WA1 1DP Lule S-958 22
Mexico
3 4 5
Antonio Moreno
Mataderos 2312
Mexico UK Sweden
Ana Trujillo Ana Trujillo Emparedados y helados Antonio Moreno Taquera Antonio Moreno
05023
Mexico
4 5
UK Sweden
Note: Be very careful when deleting records. You cannot undo this statement!
Demo Database
In this tutorial we will use the well-known Northwind sample database. Below is a selection from the "Customers" table:
CustomerID 1 CustomerName Alfreds Futterkiste ContactName Maria Anders Address Obere Str. 57 City Berlin PostalCode Country 12209 Germany
Ana Trujillo
Mexico
3 4 5
Antonio Moreno
Mataderos 2312
Mexico UK Sweden
Example
SELECT TOP 2 * FROM Customers;
Example
SELECT TOP 50 PERCENT * FROM Customers;
Demo Database
In this tutorial we will use the well-known Northwind sample database. Below is a selection from the "Customers" table:
CustomerID 1 CustomerName Alfreds Futterkiste Ana Trujillo Emparedados y helados Antonio Moreno Taquera Around the Horn Berglunds snabbkp ContactName Maria Anders Address Obere Str. 57 City Berlin PostalCode Country 12209 Germany
Ana Trujillo
Avda. de la Mxico 05021 Constitucin 2222 D.F. Mxico 05023 D.F. London WA1 1DP Lule S-958 22
Mexico
3 4 5
Antonio Moreno
Mataderos 2312
Mexico UK Sweden
The following SQL statement selects all customers with a City starting with the letter "s":
Example
SELECT * FROM Customers WHERE City LIKE 's%';
Tip: The "%" sign is used to define wildcards (missing letters) both before and after the pattern. You will learn more about wildcards in the next chapter. The following SQL statement selects all customers with a City ending with the letter "s":
Example
SELECT * FROM Customers WHERE City LIKE '%s';
The following SQL statement selects all customers with a Country containing the pattern "land":
Example
SELECT * FROM Customers WHERE Country LIKE '%land%';
Using the NOT keyword allows you to select records that does NOT match the pattern. The following SQL statement selects all customers with a Country NOT containing the pattern "land":
Example
SELECT * FROM Customers WHERE Country NOT LIKE '%land%';
SQL Wildcard
A wildcard character can be used to substitute for any other character(s) in a string.
Demo Database
In this tutorial we will use the well-known Northwind sample database. Below is a selection from the "Customers" table: CustomerID CustomerName ContactName Address 1 Alfreds Futterkiste Maria Anders Obere Str. 57 2 3 4 5 Ana Trujillo Emparedados y helados Antonio Moreno Taquera Around the Horn Berglunds snabbkp Ana Trujillo Antonio Moreno Thomas Hardy Christina Berglund Avda. de la Constitucin 2222 Mataderos 2312 120 Hanover Sq. City Berlin PostalCode Country 12209 Germany Mexico Mexico
Berguvsvgen 8 Lule
Example
SELECT * FROM Customers WHERE City LIKE 'ber%';
The following SQL statement selects all customers with a City containing the pattern "es":
Example
SELECT * FROM Customers WHERE City LIKE '%es%';
Example
SELECT * FROM Customers WHERE City LIKE '_erlin';
The following SQL statement selects all customers with a City starting with "L", followed by any character, followed by "n", followed by any character, followed by "on":
Example
SELECT * FROM Customers WHERE City LIKE 'L_n_on';
Example
SELECT * FROM Customers WHERE City LIKE '[bsp]%';
The following SQL statement selects all customers with a City starting with "a", "b", or "c":
Example
SELECT * FROM Customers WHERE City LIKE '[a-c]%';
The following SQL statement selects all customers with a City NOT starting with "b", "s", or "p":
Example
SELECT * FROM Customers WHERE City LIKE '[!bsp]%';
SQL IN Operator
The IN Operator
The IN operator allows you to specify multiple values in a WHERE clause.
SQL IN Syntax SELECT column_name(s) FROM table_name WHERE column_name IN (value1,value2,...);
Demo Database
In this tutorial we will use the well-known Northwind sample database. Below is a selection from the "Customers" table:
CustomerID 1 CustomerName Alfreds Futterkiste Ana Trujillo Emparedados y helados Antonio Moreno Taquera Around the Horn Berglunds snabbkp ContactName Maria Anders Address Obere Str. 57 City Berlin PostalCode Country 12209 Germany
Ana Trujillo
Avda. de la Mxico 05021 Constitucin 2222 D.F. Mxico 05023 D.F. London WA1 1DP Lule S-958 22
Mexico
3 4 5
Antonio Moreno
Mataderos 2312
Mexico UK Sweden
IN Operator Example
The following SQL statement selects all customers with a City of "Paris" or "London":
Example
SELECT * FROM Customers WHERE City IN ('Paris','London');
Demo Database
In this tutorial we will use the well-known Northwind sample database. Below is a selection from the "Products" table:
ProductID ProductName SupplierID CategoryID Unit Price
1 2 3 4 5
1 1 1
1 1 2 2 2
Example
SELECT * FROM Products WHERE Price BETWEEN 10 AND 20;
Example
SELECT * FROM Products WHERE Price NOT BETWEEN 10 AND 20;
Example
SELECT * FROM Products WHERE (Price BETWEEN 10 AND 20) AND NOT CategoryID IN (1,2,3);
Example
SELECT * FROM Products WHERE ProductName BETWEEN 'C' AND 'M';
Example
SELECT * FROM Products WHERE ProductName NOT BETWEEN 'C' AND 'M';
Sample Table
Below is a selection from the "Orders" table:
OrderID CustomerID EmployeeID OrderDate ShipperID 10248 10249 90 81 5 6 7/4/1996 3 7/5/1996 1
34 84 76
4 3 4
Example
SELECT * FROM Orders WHERE OrderDate BETWEEN #07/04/1996# AND #07/09/1996#;
Notice that the BETWEEN operator can produce different result in different databases! In some databases, BETWEEN selects fields that are between and excluding the test values. In other databases, BETWEEN selects fields that are between and including the test values. And in other databases, BETWEEN selects fields between the test values, including the first test value and excluding the last test value. Therefore: Check how your database treats the BETWEEN operator!
SQL Aliases
SQL aliases are used to temporarily rename a table or a column heading.
SQL Aliases
SQL aliases are used to give a database table, or a column in a table, a temporary name. Basically aliases are created to make column names more readable.
SQL Alias Syntax for Columns SELECT column_name AS alias_name FROM table_name; SQL Alias Syntax for Tables SELECT column_name(s) FROM table_name AS alias_name;
Demo Database
In this tutorial we will use the well-known Northwind sample database. Below is a selection from the "Customers" table:
CustomerID 1 2 CustomerName Alfreds Futterkiste ContactName Address City Berlin PostalCode Country 12209 05021 Germany Mexico
Ana Trujillo Ana Trujillo Emparedados y helados Antonio Moreno Taquera Antonio Moreno
05023
Mexico
10645
34
1997-08-26 1
Example
SELECT CustomerName AS Customer, ContactName AS [Contact Person] FROM Customers;
In the following SQL statement we combine four columns (Address, City, PostalCode, and Country) and create an alias named "Address":
Example
SELECT CustomerName, Address+', '+City+', '+PostalCode+', '+Country AS Address FROM Customers;
Example
SELECT o.OrderID, o.OrderDate, c.CustomerName FROM Customers AS c, Orders AS o WHERE c.CustomerName='Alfreds Futterkiste';
Example
SELECT Orders.OrderID, Orders.OrderDate, Customers.CustomerName FROM Customers, Orders WHERE Customers.CustomerName='Alfreds Futterkiste';
There are more than one table involved in a query Functions are used in the query Column names are big or not very readable Two or more columns are combined together
SQL Joins
SQL joins are used to combine rows from two or more tables.
SQL JOIN
An SQL JOIN clause is used to combine rows from two or more tables, based on a common field between them. The most common type of join is: SQL INNER JOIN (simple join). An SQL INNER JOIN return all rows from multiple tables where the join condition is met. Let's look at a selection from the "Orders" table: OrderID 10308 2 10309 37 10310 77 CustomerID OrderDate 1996-09-18 1996-09-19 1996-09-20
Then, have a look at a selection from the "Customers" table: CustomerID CustomerName ContactName Country
1 2 3
Notice that the "CustomerID" column in the "Orders" table refers to the customer in the "Customers" table. The relationship between the two tables above is the "CustomerID" column. Then, if we run the following SQL statement (that contains an INNER JOIN):
Example
SELECT Orders.OrderID, Customers.CustomerName, Orders.OrderDate FROM Orders INNER JOIN Customers ON Orders.CustomerID=Customers.CustomerID;
it will produce something like this: OrderID 10308 10365 10383 10355 10278 CustomerName Ana Trujillo Emparedados y helados Antonio Moreno Taquera Around the Horn Around the Horn Berglunds snabbkp OrderDate 9/18/1996 11/27/1996 12/16/1996 11/15/1996 8/12/1996
INNER JOIN: Returns all rows when there is at least one match in BOTH tables LEFT JOIN: Return all rows from the left table, and the matched rows from the right table RIGHT JOIN: Return all rows from the right table, and the matched rows from the left table FULL JOIN: Return all rows when there is a match in ONE of the tables
or:
SELECT column_name(s) FROM table1 JOIN table2 ON table1.column_name=table2.column_name;
Demo Database
In this tutorial we will use the well-known Northwind sample database. Below is a selection from the "Customers" table:
CustomerID CustomerName ContactName Address City PostalCode Country
Berlin
12209
Germany
Ana Trujillo
Mexico
Antonio Moreno
Mataderos 2312
Mexico
Example
SELECT Customers.CustomerName, Orders.OrderID FROM Customers INNER JOIN Orders ON Customers.CustomerID=Orders.CustomerID ORDER BY Customers.CustomerName;
Note: The INNER JOIN keyword selects all rows from both tables as long as there is a match between the columns. If there are rows in the "Customers" table that do not have matches in "Orders", these customers will NOT be listed.
or:
SELECT column_name(s) FROM table1 LEFT OUTER JOIN table2 ON table1.column_name=table2.column_name;
Demo Database
In this tutorial we will use the well-known Northwind sample database. Below is a selection from the "Customers" table:
CustomerID CustomerName ContactName Address City PostalCode Country
Berlin
12209
Germany
Ana Trujillo
Mexico
Antonio Moreno
Mataderos 2312
Mexico
Example
SELECT Customers.CustomerName, Orders.OrderID FROM Customers LEFT JOIN Orders ON Customers.CustomerID=Orders.CustomerID ORDER BY Customers.CustomerName;
Note: The LEFT JOIN keyword returns all the rows from the left table (Customers), even if there are no matches in the right table (Orders).
or:
SELECT column_name(s) FROM table1 RIGHT OUTER JOIN table2 ON table1.column_name=table2.column_name;
Demo Database
In this tutorial we will use the well-known Northwind sample database. Below is a selection from the "Customers" table:
CustomerID CustomerName ContactName Address City PostalCode Country
Berlin
12209
Germany
Ana Trujillo
Mexico
Antonio Moreno
Mataderos 2312
Mexico
Example
SELECT Customers.CustomerName, Orders.OrderID FROM Customers RIGHT JOIN Orders ON Customers.CustomerID=Orders.CustomerID ORDER BY Customers.CustomerName;
Note: The RIGHT JOIN keyword returns all the rows from the right table (Orders), even if there are no matches in the left table (Customers).
Demo Database
In this tutorial we will use the well-known Northwind sample database. Below is a selection from the "Customers" table:
CustomerID 1 CustomerName Alfreds Futterkiste Ana Trujillo Emparedados y helados ContactName Address City Berlin PostalCode Country 12209 Germany
Ana Trujillo
Mexico
Antonio Moreno
Mataderos 2312
Mexico
Note: The FULL OUTER JOIN keyword returns all the rows from the left table (Customers), and all the rows from the right table (Orders). 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.
Note: The UNION operator selects only distinct values by default. To allow duplicate values, use the ALL keyword with UNION.
SQL UNION ALL Syntax SELECT column_name(s) FROM table1 UNION ALL SELECT column_name(s) FROM table2;
PS: The column names in the result-set of a UNION are usually equal to the column names in the first SELECT statement in the UNION.
Demo Database
In this tutorial we will use the well-known Northwind sample database. Below is a selection from the "Customers" table:
CustomerID 1 CustomerName Alfreds Futterkiste Ana Trujillo Emparedados y helados Antonio Moreno Taquera ContactName Address City Berlin PostalCode Country 12209 Germany
Ana Trujillo
Mexico
Antonio Moreno
Mataderos 2312
Mexico
49 Gilbert St. Londona P.O. Box 78934 707 Oxford Rd. New Orleans
70117
USA
Regina Murphy
USA
Example
SELECT City FROM Customers UNION SELECT City FROM Suppliers ORDER BY City;
Note: UNION cannot be used to list ALL cities from the two tables. If several customers and suppliers share the same city, each city will only be listed once. UNION selects only distinct values. Use UNION ALL to also select duplicate values!
Example
SELECT City FROM Customers UNION ALL SELECT City FROM Suppliers ORDER BY City;
Example
SELECT City, Country FROM Customers WHERE Country='Germany' UNION ALL SELECT City, Country FROM Suppliers WHERE Country='Germany' ORDER BY City;
Or we can copy only the columns we want into the new table:
SELECT column_name(s) INTO newtable [IN externaldb] FROM table1;
Tip: The new table will be created with the column-names and types as defined in the SELECT statement. You can apply new names using the AS clause.
Copy data from more than one table into the new table:
SELECT Customers.CustomerName, Orders.OrderID INTO CustomersOrderBackup2013 FROM Customers LEFT JOIN Orders ON Customers.CustomerID=Orders.CustomerID;
Tip: The SELECT INTO statement can also be used to create a new, empty table using the schema of another. Just add a WHERE clause that causes the query to return no data:
SELECT * INTO newtable FROM table1 WHERE 1=0;
We can copy all columns from one table to another, existing table:
INSERT INTO table2 SELECT * FROM table1;
Or we can copy only the columns we want to into another, existing table:
INSERT INTO table2 (column_name(s)) SELECT column_name(s) FROM table1;
INSERT INTO Customers (CustomerName, Country) SELECT SupplierName, Country FROM Suppliers WHERE Country='Germany';
The column_name parameters specify the names of the columns of the table. The data_type parameter specifies what type of data the column can hold (e.g. varchar, integer, decimal, date, etc.). The size parameter specifies the maximum length of the column of the table. Tip: For an overview of the data types available in MS Access, MySQL, and SQL Server, go to our complete Data Types Reference.
The PersonID column is of type int and will hold an integer. The LastName, FirstName, Address, and City columns are of type varchar and will hold characters, and the maximum length for these fields is 255 characters. The empty "Persons" table will now look like this:
PersonID LastName FirstName Address City
Tip: The empty table can be filled with data with the INSERT INTO statement.
SQL Constraints
SQL Constraints
SQL constraints are used to specify rules for the data in a table. If there is any violation between the constraint and the data action, the action is aborted by the constraint. Constraints can be specified when the table is created (inside the CREATE TABLE statement) or after the table is created (inside the ALTER TABLE statement).
SQL CREATE TABLE + CONSTRAINT Syntax CREATE TABLE table_name ( column_name1 data_type(size) constraint_name, column_name2 data_type(size) constraint_name, column_name3 data_type(size) constraint_name, .... );
NOT NULL - Indicates that a column cannot store NULL value UNIQUE - Ensures that each row for a column must have a unique value PRIMARY KEY - A combination of a NOT NULL and UNIQUE. Ensures that a column (or combination of two or more columns) have an unique identity which helps to find a particular record in a table more easily and quickly FOREIGN KEY - Ensure the referential integrity of the data in one table to match values in another table CHECK - Ensures that the value in a column meets a specific condition DEFAULT - Specifies a default value when specified none for this column
City varchar(255) ) To allow naming of a PRIMARY KEY constraint, and for defining a PRIMARY KEY constraint on multiple columns, use the following SQL syntax: MySQL / SQL Server / Oracle / MS Access: CREATE TABLE Persons ( P_Id int NOT NULL, LastName varchar(255) NOT NULL, FirstName varchar(255), Address varchar(255), City varchar(255), CONSTRAINT pk_PersonID PRIMARY KEY (P_Id,LastName) ) Note: In the example above there is only ONE PRIMARY KEY (pk_PersonID). However, the value of the pk_PersonID is made up of two columns (P_Id and LastName).
The "Orders" table: O_Id 1 2 3 4 OrderNo 77895 44678 22456 24562 P_Id 3 3 2 1
Note that the "P_Id" column in the "Orders" table points to the "P_Id" column in the "Persons" table. The "P_Id" column in the "Persons" table is the PRIMARY KEY in the "Persons" table. The "P_Id" column in the "Orders" table is a FOREIGN KEY in the "Orders" table. The FOREIGN KEY constraint is used to prevent actions that would destroy links between tables. The FOREIGN KEY constraint also prevents invalid data from being inserted into the foreign key column, because it has to be one of the values contained in the table it points to.
CREATE TABLE Orders ( O_Id int NOT NULL, OrderNo int NOT NULL, P_Id int, PRIMARY KEY (O_Id), FOREIGN KEY (P_Id) REFERENCES Persons(P_Id) )
SQL Server / Oracle / MS Access:
CREATE TABLE Orders ( O_Id int NOT NULL PRIMARY KEY, OrderNo int NOT NULL, P_Id int FOREIGN KEY REFERENCES Persons(P_Id) )
To allow naming of a FOREIGN KEY constraint, and for defining a FOREIGN KEY constraint on multiple columns, use the following SQL syntax: MySQL / SQL Server / Oracle / MS Access:
CREATE TABLE Orders ( O_Id int NOT NULL, OrderNo int NOT NULL, P_Id int, PRIMARY KEY (O_Id), CONSTRAINT fk_PerOrders FOREIGN KEY (P_Id) REFERENCES Persons(P_Id) )
ALTER TABLE Orders ADD CONSTRAINT fk_PerOrders FOREIGN KEY (P_Id) REFERENCES Persons(P_Id)
If you define a CHECK constraint on a table it can limit the values in certain columns based on values in other columns in the row.
CREATE TABLE Persons ( P_Id int NOT NULL, LastName varchar(255) NOT NULL, FirstName varchar(255), Address varchar(255), City varchar(255), CHECK (P_Id>0) )
SQL Server / Oracle / MS Access:
CREATE TABLE Persons ( P_Id int NOT NULL CHECK (P_Id>0), LastName varchar(255) NOT NULL, FirstName varchar(255), Address varchar(255), City varchar(255) )
To allow naming of a CHECK constraint, and for defining a CHECK constraint on multiple columns, use the following SQL syntax: MySQL / SQL Server / Oracle / MS Access:
CREATE TABLE Persons ( P_Id int NOT NULL, LastName varchar(255) NOT NULL, FirstName varchar(255), Address varchar(255), City varchar(255), CONSTRAINT chk_Person CHECK (P_Id>0 AND City='Sandnes') )
To create a CHECK constraint on the "P_Id" column when the table is already created, use the following SQL: MySQL / SQL Server / Oracle / MS Access:
ALTER TABLE Persons ADD CONSTRAINT chk_Person CHECK (P_Id>0 AND City='Sandnes')
The following SQL creates a DEFAULT constraint on the "City" column when the "Persons" table is created: My SQL / SQL Server / Oracle / MS Access:
CREATE TABLE Persons ( P_Id int NOT NULL, LastName varchar(255) NOT NULL, FirstName varchar(255), Address varchar(255), City varchar(255) DEFAULT 'Sandnes' )
The DEFAULT constraint can also be used to insert system values, by using functions like GETDATE():
CREATE TABLE Orders ( O_Id int NOT NULL, OrderNo int NOT NULL, P_Id int, OrderDate date DEFAULT GETDATE() )
MySQL:
The CREATE INDEX statement is used to create indexes in tables. Indexes allow the database application to find data fast; without reading the whole table.
Indexes
An index can be created in a table to find data more quickly and efficiently. The users cannot see the indexes, they are just used to speed up searches/queries. Note: Updating a table with indexes takes more time than updating a table without (because the indexes also need an update). So you should only create indexes on columns (and tables) that will be frequently searched against.
Note: The syntax for creating indexes varies amongst different databases. Therefore: Check the syntax for creating indexes in your database.
Indexes, tables, and databases can easily be deleted/removed with the DROP statement.
Now we want to add a column named "DateOfBirth" in the "Persons" table. We use the following SQL statement:
P_Id 1 2 3
CREATE TABLE Persons ( ID int NOT NULL AUTO_INCREMENT, LastName varchar(255) NOT NULL, FirstName varchar(255), Address varchar(255), City varchar(255), PRIMARY KEY (ID) )
MySQL uses the AUTO_INCREMENT keyword to perform an auto-increment feature. By default, the starting value for AUTO_INCREMENT is 1, and it will increment by 1 for each new record.
To let the AUTO_INCREMENT sequence start with another value, use the following SQL statement:
CREATE TABLE Persons ( ID int IDENTITY(1,1) PRIMARY KEY, LastName varchar(255) NOT NULL, FirstName varchar(255), Address varchar(255), City varchar(255) )
The MS SQL Server uses the IDENTITY keyword to perform an auto-increment feature. In the example above, the starting value for IDENTITY is 1, and it will increment by 1 for each new record. Tip: To specify that the "ID" column should start at value 10 and increment by 5, change it to IDENTITY(10,5). To insert a new record into the "Persons" table, we will NOT have to specify a value for the "ID" column (a unique value will be added automatically):
The following SQL statement defines the "ID" column to be an auto-increment primary key field in the "Persons" table:
CREATE TABLE Persons ( ID Integer PRIMARY KEY AUTOINCREMENT, LastName varchar(255) NOT NULL, FirstName varchar(255), Address varchar(255), City varchar(255) )
The MS Access uses the AUTOINCREMENT keyword to perform an auto-increment feature. By default, the starting value for AUTOINCREMENT is 1, and it will increment by 1 for each new record. Tip: To specify that the "ID" column should start at value 10 and increment by 5, change the autoincrement to AUTOINCREMENT(10,5). To insert a new record into the "Persons" table, we will NOT have to specify a value for the "ID" column (a unique value will be added automatically):
To insert a new record into the "Persons" table, we will have to use the nextval function (this function retrieves the next value from seq_person sequence):
SQL Views
Previous Next Chapter
A view is a virtual table. This chapter shows how to create, update, and delete a view.
If you have the Northwind database you can see that it has several views installed by default. The view "Current Product List" lists all active products (products that are not discontinued) from the "Products" table. The view is created with the following SQL:
CREATE VIEW [Current Product List] AS SELECT ProductID,ProductName FROM Products WHERE Discontinued=No
We can query the view above as follows:
CREATE VIEW [Products Above Average Price] AS SELECT ProductName,UnitPrice FROM Products WHERE UnitPrice>(SELECT AVG(UnitPrice) FROM Products)
We can query the view above as follows:
CREATE VIEW [Category Sales For 1997] AS SELECT DISTINCT CategoryName,Sum(ProductSales) AS CategorySales FROM [Product Sales for 1997] GROUP BY CategoryName
We can query the view above as follows:
CREATE VIEW [Current Product List] AS SELECT ProductID,ProductName,Category FROM Products WHERE Discontinued=No
SQL Dates
The most difficult part when working with dates is to be sure that the format of the date you are trying to insert, matches the format of the date column in the database. As long as your data contains only the date portion, your queries will work as expected. However, if a time portion is involved, it gets complicated. Before talking about the complications of querying for dates, we will look at the most important builtin functions for working with dates.
The following table lists the most important built-in date functions in MySQL: Function NOW() CURDATE() CURTIME() DATE() EXTRACT() DATE_ADD() DATE_SUB() DATEDIFF() DATE_FORMAT() Description Returns the current date and time Returns the current date Returns the current time Extracts the date part of a date or date/time expression Returns a single part of a date/time Adds a specified time interval to a date Subtracts a specified time interval from a date Returns the number of days between two dates Displays date/time data in different formats
DATE - format YYYY-MM-DD DATETIME - format: YYYY-MM-DD HH:MM:SS TIMESTAMP - format: YYYY-MM-DD HH:MM:SS YEAR - format YYYY or YY
SQL Server comes with the following data types for storing a date or a date/time value in the database:
DATE - format YYYY-MM-DD DATETIME - format: YYYY-MM-DD HH:MM:SS SMALLDATETIME - format: YYYY-MM-DD HH:MM:SS TIMESTAMP - format: a unique number
Note: The date types are chosen for a column when you create a new table in your database! For an overview of all data types available, go to our complete Data Types reference.
Now we want to select the records with an OrderDate of "2008-11-11" from the table above. We use the following SELECT statement:
Now, assume that the "Orders" table looks like this (notice the time component in the "OrderDate" column): OrderId 1 ProductName Geitost OrderDate 2008-11-11 13:23:44
2 3 4
1 2 3
Suppose that the "Address" column in the "Persons" table is optional. This means that if we insert a record with no value for the "Address" column, the "Address" column will be saved with a NULL value. How can we test for NULL values? It is not possible to test for NULL values with comparison operators, such as =, <, or <>. We will have to use the IS NULL and IS NOT NULL operators instead.
SQL IS NULL
How do we select only the records with NULL values in the "Address" column? We will have to use the IS NULL operator:
LastName Svendson
FirstName Tove
Address Borgvn 23
In the next chapter we will look at the ISNULL(), NVL(), IFNULL() and COALESCE() functions.
Suppose that the "UnitsOnOrder" column is optional, and may contain NULL values. We have the following SELECT statement:
Oracle Oracle does not have an ISNULL() function. However, we can use the NVL() function to achieve the same result:
BINARY(n) BOOLEAN VARBINARY(n) or BINARY VARYING(n) INTEGER(p) SMALLINT INTEGER BIGINT DECIMAL(p,s)
Binary string. Fixed-length n Stores TRUE or FALSE values Binary string. Variable length. Maximum length n
Integer numerical (no decimal). Precision p Integer numerical (no decimal). Precision 5 Integer numerical (no decimal). Precision 10 Integer numerical (no decimal). Precision 19 Exact numerical, precision p, scale s. Example: decimal(5,2) is a number that has 3 digits before the decimal and 2 digits after the decimal Exact numerical, precision p, scale s. (Same as DECIMAL) Approximate numerical, mantissa precision p. A floating number in base 10 exponential notation. The size argument for this type consists of a single number specifying the minimum precision Approximate numerical, mantissa precision 7 Approximate numerical, mantissa precision 16 Approximate numerical, mantissa precision 16 Stores year, month, and day values Stores hour, minute, and second values Stores year, month, day, hour, minute, and second values Composed of a number of integer fields, representing a period of time, depending on the type of interval A set-length and ordered collection of elements A variable-length and unordered collection of elements Stores XML data
NUMERIC(p,s) FLOAT(p)
float
Number (single)
Number
binary object
Blob Text
Binary Varbinary
Note: Data types might have different names in different database. And even if the name is the same, the size and other details may be different! Always check the docum
Double Currency
Double precision floating-point. Will handle most decimals Use for currency. Holds up to 15 digits of whole dollars, plus 4 decimal places.Tip: You can choose which country's currency to use AutoNumber fields automatically give each record its own number, usually starting at 1 Use for dates and times
8 bytes 8 bytes
AutoNumber
4 bytes
Date/Time Yes/No
8 bytes
A logical field can be displayed as Yes/No, True/False, or On/Off. In code, use the 1 bit constants True and False (equivalent to -1 and 0). Note: Null values are not allowed in Yes/No fields Can store pictures, audio, video, or other BLOBs (Binary Large OBjects) Contain links to other files, including web pages Let you type a list of options, which can then be chosen from a drop-down list 4 bytes up to 1GB
VARCHAR(size)
value is inserted that is not in the list, a blank value will be inserted. Note: The values are sorted in the order you enter them. You enter the possible values in this format: ENUM('X','Y','Z') SET Similar to ENUM except that SET may contain up to 64 list items and can store more than one choice
Number types: Data type TINYINT(size) Description -128 to 127 normal. 0 to 255 UNSIGNED*. The maximum number of digits may be specified in parenthesis -32768 to 32767 normal. 0 to 65535 UNSIGNED*. The maximum number of digits may be specified in parenthesis -8388608 to 8388607 normal. 0 to 16777215 UNSIGNED*. The maximum number of digits may be specified in parenthesis -2147483648 to 2147483647 normal. 0 to 4294967295 UNSIGNED*. The maximum number of digits may be specified in parenthesis -9223372036854775808 to 9223372036854775807 normal. 0 to 18446744073709551615 UNSIGNED*. The maximum number of digits may be specified in parenthesis A small number with a floating decimal point. The maximum number of digits may be specified in the size parameter. The maximum number of digits to the right of the decimal point is specified in the d parameter A large number with a floating decimal point. The maximum number of digits may be specified in the size parameter. The maximum number of digits to the right of the decimal point is specified in the d parameter A DOUBLE stored as a string , allowing for a fixed decimal point. The maximum number of digits may be specified in the size parameter. The maximum number of digits to the right of the decimal point is specified in the d parameter
SMALLINT(size)
MEDIUMINT(size)
INT(size)
BIGINT(size)
FLOAT(size,d)
DOUBLE(size,d)
DECIMAL(size,d)
*The integer types have an extra option called UNSIGNED. Normally, the integer goes from an negative to positive value. Adding the UNSIGNED attribute will move that range up so it starts at zero instead of a negative number. Date types: Data type DATE() Description A date. Format: YYYY-MM-DD Note: The supported range is from '1000-01-01' to '9999-12-31'
DATETIME()
*A date and time combination. Format: YYYY-MM-DD HH:MM:SS Note: The supported range is from '1000-01-01 00:00:00' to '9999-12-31 23:59:59'
TIMESTAMP()
*A timestamp. TIMESTAMP values are stored as the number of seconds since the Unix epoch ('1970-01-01 00:00:00' UTC). Format: YYYY-MM-DD HH:MM:SS Note: The supported range is from '1970-01-01 00:00:01' UTC to '2038-01-09 03:14:07' UTC
TIME()
A time. Format: HH:MM:SS Note: The supported range is from '-838:59:59' to '838:59:59'
YEAR()
A year in two-digit or four-digit format. Note: Values allowed in four-digit format: 1901 to 2155. Values allowed in two-digit format: 70 to 69, representing years from 1970 to 2069
*Even if DATETIME and TIMESTAMP return the same format, they work very differently. In an INSERT or UPDATE query, the TIMESTAMP automatically set itself to the current date and time. TIMESTAMP also accepts various formats, like YYYYMMDDHHMMSS, YYMMDDHHMMSS, YYYYMMDD, or YYMMDD.
varchar(max)
text
Fixed width Unicode string. Maximum 4,000 characters Variable width Unicode string. Maximum 4,000 characters Variable width Unicode string. Maximum 536,870,912 characters Variable width Unicode string. Maximum 2GB of text data Allows 0, 1, or NULL
binary(n) varbinary varbinary(max) image Number types: Data type tinyint smallint int bigint
Fixed width binary string. Maximum 8,000 bytes Variable width binary string. Maximum 8,000 bytes Variable width binary string. Maximum 2GB Variable width binary string. Maximum 2GB
Description Allows whole numbers from 0 to 255 Allows whole numbers between -32,768 and 32,767 Allows whole numbers between -2,147,483,648 and 2,147,483,647 Allows whole numbers between -9,223,372,036,854,775,808 and 9,223,372,036,854,775,807 Fixed precision and scale numbers. Allows numbers from -10^38 +1 to 10^38 1. The p parameter indicates the maximum total number of digits that can be stored (both to the left and to the right of the decimal point). p must be a value from 1 to 38. Default is 18. The s parameter indicates the maximum number of digits stored to the right of the decimal point. s must be a value from 0 to p. Default value is 0
decimal(p,s)
5-17 bytes
numeric(p,s)
Fixed precision and scale numbers. Allows numbers from -10^38 +1 to 10^38 1. The p parameter indicates the maximum total number of digits that can be stored (both to the left and to the right of the decimal point). p must be a value from 1 to 38. Default is 18. The s parameter indicates the maximum number of digits stored to the right of the decimal point. s must be a value from 0 to p. Default value is 0
5-17 bytes
Monetary data from -214,748.3648 to 214,748.3647 Monetary data from -922,337,203,685,477.5808 to 922,337,203,685,477.5807 Floating precision number data from -1.79E + 308 to 1.79E + 308. The n parameter indicates whether the field should hold 4 or 8 bytes. float(24) holds a 4-byte field and float(53) holds an 8-byte field. Default value of n is 53.
4 bytes
Description From January 1, 1753 to December 31, 9999 with an accuracy of 3.33 milliseconds From January 1, 0001 to December 31, 9999 with an accuracy of 100 nanoseconds From January 1, 1900 to June 6, 2079 with an accuracy of 1 minute Store a date only. From January 1, 0001 to December 31, 9999 Store a time only to an accuracy of 100 nanoseconds The same as datetime2 with the addition of a time zone offset
Storage 8 bytes
datetime2
6-8 bytes
timestamp
Stores a unique number that gets updated every time a row gets created or modified. The timestamp value is based upon an internal clock and does not correspond to real time. Each table may have only one timestamp variable
Other data types: Data type sql_variant uniqueidentifier xml cursor table Description Stores up to 8,000 bytes of data of various data types, except text, ntext, and timestamp Stores a globally unique identifier (GUID) Stores XML formatted data. Maximum 2GB Stores a reference to a cursor used for database operations Stores a result-set for later processing
SQL Aggregate Functions SQL aggregate functions return a single value, calculated from values in a column. Useful aggregate functions:
AVG() - Returns the average value COUNT() - Returns the number of rows FIRST() - Returns the first value LAST() - Returns the last value MAX() - Returns the largest value MIN() - Returns the smallest value SUM() - Returns the sum
SQL Scalar functions SQL scalar functions return a single value, based on the input value. Useful scalar functions:
UCASE() - Converts a field to upper case LCASE() - Converts a field to lower case MID() - Extract characters from a text field LEN() - Returns the length of a text field ROUND() - Rounds a numeric field to the number of decimals specified NOW() - Returns the current system date and time FORMAT() - Formats how a field is to be displayed
Tip: The aggregate functions and the scalar functions will be explained in details in the next chapters. SQL AVG() Function
The AVG() Function The AVG() function returns the average value of a numeric column. SQL AVG() Syntax SELECT AVG(column_name) FROM table_name
Demo Database In this tutorial we will use the well-known Northwind sample database. Below is a selection from the "Products" table: ProductID ProductName 1 2 3 4 5 Chais Chang Aniseed Syrup SupplierID CategoryID Unit 1 1 1 1 1 2 2 2 Price
SQL AVG() Example The following SQL statement gets the average value of the "Price" column from the "Products" table: Example SELECT AVG(Price) AS PriceAverage FROM Products;
Try it yourself The following SQL statement selects the "ProductName" and "Price" records that have an above average price: Example SELECT ProductName, Price FROM Products WHERE Price>(SELECT AVG(Price) FROM Products);
The COUNT() function returns the number of rows that matches a specified criteria.
SQL COUNT(column_name) Syntax The COUNT(column_name) function returns the number of values (NULL values will not be counted) of the specified column: SELECT COUNT(column_name) FROM table_name; SQL COUNT(*) Syntax The COUNT(*) function returns the number of records in a table: SELECT COUNT(*) FROM table_name; SQL COUNT(DISTINCT column_name) Syntax The COUNT(DISTINCT column_name) function returns the number of distinct values of the specified column: SELECT COUNT(DISTINCT column_name) FROM table_name; Note: COUNT(DISTINCT) works with ORACLE and Microsoft SQL Server, but not with Microsoft Access.
Demo Database In this tutorial we will use the well-known Northwind sample database. Below is a selection from the "Orders" table: OrderID CustomerID EmployeeID OrderDate ShipperID 10265 10266 10267 7 87 25 2 3 4 1996-07-25 1 1996-07-26 3 1996-07-29 1
SQL COUNT(column_name) Example The following SQL statement counts the number of orders from "CustomerID"=7 from the "Orders" table: Example SELECT COUNT(CustomerID) AS OrdersFromCustomerID7 FROM Orders WHERE CustomerID=7;
Try it yourself
SQL COUNT(*) Example The following SQL statement counts the total number of orders in the "Orders" table: Example SELECT COUNT(*) AS NumberOfOrders FROM Orders; SQL COUNT(DISTINCT column_name) Example The following SQL statement counts the number of unique customers in the "Orders" table: Example
The FIRST() Function The FIRST() function returns the first value of the selected column. SQL FIRST() Syntax SELECT FIRST(column_name) FROM table_name; Note: The FIRST() function is only supported in MS Access.
SQL FIRST() Workaround in SQL Server, MySQL and Oracle SQL Server Syntax SELECT TOP 1 column_name FROM table_name ORDER BY column_name ASC; Example SELECT TOP 1 CustomerName FROM Customers ORDER BY CustomerID ASC; MySQL Syntax SELECT column_name FROM table_name ORDER BY column_name ASC LIMIT 1; Example SELECT CustomerName FROM Customers ORDER BY CustomerID ASC LIMIT 1;
Oracle Syntax SELECT column_name FROM table_name ORDER BY column_name ASC WHERE ROWNUM <=1; Example SELECT CustomerName FROM Customers ORDER BY CustomerID ASC WHERE ROWNUM <=1;
Demo Database In this tutorial we will use the well-known Northwind sample database. Below is a selection from the "Customers" table: CustomerID CustomerName 1 Alfreds Futterkiste Ana Trujillo Emparedados y helados Antonio Moreno Taquera Around the Horn Berglunds snabbkp ContactName Address Maria Anders Obere Str. 57 City Berlin PostalCode Country 12209 Germany
Ana Trujillo
Avda. de la Mxico 05021 Constitucin 2222 D.F. Mxico 05023 D.F. London WA1 1DP Lule S-958 22
Mexico
3 4 5
Antonio Moreno
Mataderos 2312
Mexico UK Sweden
SQL FIRST() Example The following SQL statement selects the first value of the "CustomerName" column from the "Customers" table:
The LAST() Function The LAST() function returns the last value of the selected column. SQL LAST() Syntax SELECT LAST(column_name) FROM table_name; Note: The LAST() function is only supported in MS Access.
SQL LAST() Workaround in SQL Server, MySQL and Oracle SQL Server Syntax SELECT TOP 1 column_name FROM table_name ORDER BY column_name DESC; Example SELECT TOP 1 CustomerName FROM Customers ORDER BY CustomerID DESC; MySQL Syntax SELECT column_name FROM table_name ORDER BY column_name DESC LIMIT 1; Example
SELECT CustomerName FROM Customers ORDER BY CustomerID DESC LIMIT 1; Oracle Syntax SELECT column_name FROM table_name ORDER BY column_name DESC WHERE ROWNUM <=1; Example SELECT CustomerName FROM Customers ORDER BY CustomerID DESC WHERE ROWNUM <=1;
Demo Database In this tutorial we will use the well-known Northwind sample database. Below is a selection from the "Customers" table: CustomerID CustomerName 1 Alfreds Futterkiste Ana Trujillo Emparedados y helados Antonio Moreno Taquera Around the Horn Berglunds snabbkp ContactName Address Maria Anders Obere Str. 57 City Berlin PostalCode Country 12209 Germany
Ana Trujillo
Avda. de la Mxico 05021 Constitucin 2222 D.F. Mxico 05023 D.F. London WA1 1DP Lule S-958 22
Mexico
3 4 5
Antonio Moreno
Mataderos 2312
Mexico UK Sweden
The following SQL statement selects the last value of the "CustomerName" column from the "Customers" table: Example SELECT LAST(CustomerName) AS LastCustomer FROM Customers;
The MAX() Function The MAX() function returns the largest value of the selected column. SQL MAX() Syntax SELECT MAX(column_name) FROM table_name;
Demo Database In this tutorial we will use the well-known Northwind sample database. Below is a selection from the "Products" table: ProductID ProductName 1 2 3 4 5 Chais Chang Aniseed Syrup SupplierID CategoryID Unit 1 1 1 1 1 2 2 2 Price
SQL MAX() Example The following SQL statement gets the largest value of the "Price" column from the "Products" table: Example SELECT MAX(Price) AS HighestPrice FROM Products; SQL MIN() Function Previous Next Chapter
The MIN() Function The MIN() function returns the smallest value of the selected column. SQL MIN() Syntax SELECT MIN(column_name) FROM table_name;
Demo Database In this tutorial we will use the well-known Northwind sample database. Below is a selection from the "Products" table: ProductID ProductName 1 2 3 4 Chais Chang Aniseed Syrup SupplierID CategoryID Unit 1 1 1 1 1 2 2 Price
36 boxes
25
SQL MIN() Example The following SQL statement gets the smallest value of the "Price" column from the "Products" table: Example SELECT MIN(Price) AS SmallestOrderPrice FROM Products; SQL SUM() Function Previous Next Chapter
The SUM() Function The SUM() function returns the total sum of a numeric column. SQL SUM() Syntax SELECT SUM(column_name) FROM table_name;
Demo Database In this tutorial we will use the well-known Northwind sample database. Below is a selection from the "OrderDetails" table: OrderDetailID OrderID ProductID Quantity 1 2 3 10248 10248 10248 11 42 72 12 10 5
4 5
10249 10249
14 51
9 40
SQL SUM() Example The following SQL statement finds the sum of all the "Quantity" fields for the "OrderDetails" table: Example SELECT SUM(Quantity) AS TotalItemsOrdered FROM OrderDetails; SQL GROUP BY Statement Previous Next Chapter
The GROUP BY Statement The GROUP BY statement is used in conjunction with the aggregate functions to group the result-set by one or more columns. SQL GROUP BY Syntax SELECT column_name, aggregate_function(column_name) FROM table_name WHERE column_name operator value GROUP BY column_name;
Demo Database In this tutorial we will use the well-known Northwind sample database. Below is a selection from the "Orders" table:
OrderID CustomerID EmployeeID OrderDate ShipperID 10248 10249 10250 90 81 34 5 6 4 1996-07-04 3 1996-07-05 1 1996-07-08 2
Speedy Express (503) 555-9831 United Package (503) 555-3199 Federal Shipping (503) 555-9931
And a selection from the "Employees" table: EmployeeID LastName FirstName BirthDate Photo 1 2 3 Davolio Fuller Nancy Andrew Notes
1968-12-08 EmpID1.pic Education includes a BA.... 1952-02-19 EmpID2.pic Andrew received his BTS.... 1963-08-30 EmpID3.pic Janet has a BS degree....
Leverling Janet
SQL GROUP BY Example Now we want to find the number of orders sent by each shipper. The following SQL statement counts as orders grouped by shippers: Example SELECT Shippers.ShipperName,COUNT(Orders.OrderID) AS NumberOfOrders FROM Orders LEFT JOIN Shippers ON Orders.ShipperID=Shippers.ShipperID GROUP BY ShipperName;
Try it yourself
GROUP BY More Than One Column We can also use the GROUP BY statement on more than one column, like this: Example SELECT Shippers.ShipperName, Employees.LastName, COUNT(Orders.OrderID) AS NumberOfOrders FROM ((Orders INNER JOIN Shippers ON Orders.ShipperID=Shippers.ShipperID) INNER JOIN Employees ON Orders.EmployeeID=Employees.EmployeeID) GROUP BY ShipperName,LastName; SQL HAVING Clause Previous Next Chapter
The HAVING Clause The HAVING clause was added to SQL because the WHERE keyword could not be used with aggregate functions. SQL HAVING Syntax SELECT column_name, aggregate_function(column_name) FROM table_name WHERE column_name operator value GROUP BY column_name HAVING aggregate_function(column_name) operator value;
Demo Database
In this tutorial we will use the well-known Northwind sample database. Below is a selection from the "Orders" table: OrderID CustomerID EmployeeID OrderDate ShipperID 10248 10249 10250 90 81 34 5 6 4 1996-07-04 3 1996-07-05 1 1996-07-08 2
And a selection from the "Employees" table: EmployeeID LastName FirstName BirthDate Photo 1 2 3 Davolio Fuller Nancy Andrew Notes
1968-12-08 EmpID1.pic Education includes a BA.... 1952-02-19 EmpID2.pic Andrew received his BTS.... 1963-08-30 EmpID3.pic Janet has a BS degree....
Leverling Janet
SQL HAVING Example Now we want to find if any of the customers have a total order of less than 2000. We use the following SQL statement: The following SQL statement finds if any of the employees has registered more than 10 orders: Example 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; Now we want to find the if the employees "Davolio" or "Fuller" have more than 25 orders We add an ordinary WHERE clause to the SQL statement: Example
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 SQL UCASE() Function Previous Next Chapter
The UCASE() Function The UCASE() function converts the value of a field to uppercase. SQL UCASE() Syntax SELECT UCASE(column_name) FROM table_name; Syntax for SQL Server SELECT UPPER(column_name) FROM table_name;
Demo Database In this tutorial we will use the well-known Northwind sample database. Below is a selection from the "Customers" table: CustomerID CustomerName 1 Alfreds Futterkiste Ana Trujillo Emparedados y helados Antonio Moreno Taquera ContactName Address Maria Anders Obere Str. 57 City Berlin PostalCode Country 12209 Germany
Ana Trujillo
Mexico
Antonio Moreno
Mataderos 2312
Mexico
4 5
UK Sweden
SQL UCASE() Example The following SQL statement selects the "CustomerName" and "City" columns from the "Customers" table, and converts the "CustomerName" column to uppercase: Example SELECT UCASE(CustomerName) AS Customer, City FROM Customers; SQL LCASE() Function Previous Next Chapter
The LCASE() Function The LCASE() function converts the value of a field to lowercase. SQL LCASE() Syntax SELECT LCASE(column_name) FROM table_name; Syntax for SQL Server SELECT LOWER(column_name) FROM table_name;
Demo Database In this tutorial we will use the well-known Northwind sample database. Below is a selection from the "Customers" table:
CustomerID CustomerName 1 Alfreds Futterkiste Ana Trujillo Emparedados y helados Antonio Moreno Taquera Around the Horn Berglunds snabbkp
City Berlin
Ana Trujillo
Avda. de la Mxico 05021 Constitucin 2222 D.F. Mxico 05023 D.F. London WA1 1DP Lule S-958 22
Mexico
3 4 5
Antonio Moreno
Mataderos 2312
Mexico UK Sweden
SQL LCASE() Example The following SQL statement selects the "CustomerName" and "City" columns from the "Customers" table, and converts the "CustomerName" column to lowercase: Example SELECT LCASE(CustomerName) AS Customer, City FROM Customers; SQL MID() Function Previous Next Chapter
The MID() Function The MID() function is used to extract characters from a text field. SQL MID() Syntax SELECT MID(column_name,start[,length]) FROM table_name;
Description Required. The field to extract characters from Required. Specifies the starting position (starts at 1) Optional. The number of characters to return. If omitted, the MID() function returns the rest of the text
Demo Database In this tutorial we will use the well-known Northwind sample database. Below is a selection from the "Customers" table: CustomerID CustomerName 1 Alfreds Futterkiste Ana Trujillo Emparedados y helados Antonio Moreno Taquera Around the Horn Berglunds snabbkp ContactName Address Maria Anders Obere Str. 57 City Berlin PostalCode Country 12209 Germany
Ana Trujillo
Avda. de la Mxico 05021 Constitucin 2222 D.F. Mxico 05023 D.F. London WA1 1DP Lule S-958 22
Mexico
3 4 5
Antonio Moreno
Mataderos 2312
Mexico UK Sweden
SQL MID() Example The following SQL statement selects the first four characters from the "City" column from the "Customers" table: Example
SELECT MID(City,1,4) AS ShortCity FROM Customers; SQL LEN() Function Previous Next Chapter
The LEN() Function The LEN() function returns the length of the value in a text field. SQL LEN() Syntax SELECT LEN(column_name) FROM table_name;
Demo Database In this tutorial we will use the well-known Northwind sample database. Below is a selection from the "Customers" table: CustomerID CustomerName 1 Alfreds Futterkiste Ana Trujillo Emparedados y helados Antonio Moreno Taquera Around the Horn Berglunds snabbkp ContactName Address Maria Anders Obere Str. 57 City Berlin PostalCode Country 12209 Germany
Ana Trujillo
Avda. de la Mxico 05021 Constitucin 2222 D.F. Mxico 05023 D.F. London WA1 1DP Lule S-958 22
Mexico
3 4 5
Antonio Moreno
Mataderos 2312
Mexico UK Sweden
SQL LEN() Example The following SQL statement selects the "CustomerName" and the length of the values in the "Address" column from the "Customers" table: Example SELECT CustomerName,LEN(Address) as LengthOfAddress FROM Customers; SQL ROUND() Function Previous Next Chapter
The ROUND() Function The ROUND() function is used to round a numeric field to the number of decimals specified. SQL ROUND() Syntax SELECT ROUND(column_name,decimals) FROM table_name;
Parameter
Description
column_name Required. The field to round. decimals Required. Specifies the number of decimals to be returned.
Demo Database In this tutorial we will use the well-known Northwind sample database. Below is a selection from the "Products" table: ProductID ProductName 1 Chais SupplierID CategoryID Unit 1 1 Price
10 boxes x 20 bags 18
2 3 4 5
1 1
1 2 2 2
SQL ROUND() Example The following SQL statement selects the product name and the price rounded to the neares integer from the "Products" table: Example SELECT ProductName, ROUND(Price,0) AS RoundedPrice FROM Products; SQL NOW() Function Previous Next Chapter
The NOW() Function The NOW() function returns the current system date and time. SQL NOW() Syntax SELECT NOW() FROM table_name;
Demo Database In this tutorial we will use the well-known Northwind sample database. Below is a selection from the "Products" table:
Price
SQL NOW() Example The following SQL statement selects the product name, and price for today from the "Products" table: Example SELECT ProductName, Price, Now() AS PerDate FROM Products; SQL FORMAT() Function Previous Next Chapter
The FORMAT() Function The FORMAT() function is used to format how a field is to be displayed. SQL FORMAT() Syntax SELECT FORMAT(column_name,format) FROM table_name;
Parameter
Description
format
Demo Database In this tutorial we will use the well-known Northwind sample database. Below is a selection from the "Products" table: ProductID ProductName 1 2 3 4 5 Chais Chang Aniseed Syrup SupplierID CategoryID Unit 1 1 1 1 1 2 2 2 Price
SQL FORMAT() Example The following SQL statement selects the product name, and price for today (formatted like YYYY-MMDD) from the "Products" table: Example SELECT ProductName, Price, FORMAT(Now(),'YYYY-MM-DD') AS PerDate FROM Products; SQL Quick Reference From W3Schools Previous Next Chapter
SQL Statement
Syntax
AND / OR
SELECT column_name(s) FROM table_name WHERE condition AND|OR condition ALTER TABLE table_name ADD column_name datatype or ALTER TABLE table_name DROP COLUMN column_name
ALTER TABLE
AS (alias)
SELECT column_name AS column_alias FROM table_name or SELECT column_name FROM table_name AS table_alias
BETWEEN
SELECT column_name(s) FROM table_name WHERE column_name BETWEEN value1 AND value2 CREATE DATABASE database_name CREATE TABLE table_name ( column_name1 data_type, column_name2 data_type, column_name2 data_type, ... ) CREATE INDEX index_name ON table_name (column_name) or CREATE UNIQUE INDEX index_name ON table_name (column_name)
CREATE INDEX
CREATE VIEW
CREATE VIEW view_name AS SELECT column_name(s) FROM table_name WHERE condition DELETE FROM table_name WHERE some_column=some_value or DELETE FROM table_name (Note: Deletes the entire table!!) DELETE * FROM table_name (Note: Deletes the entire table!!)
DELETE
DROP DATABASE database_name DROP INDEX table_name.index_name (SQL Server) DROP INDEX index_name ON table_name (MS Access) DROP INDEX index_name (DB2/Oracle) ALTER TABLE table_name DROP INDEX index_name (MySQL) DROP TABLE table_name SELECT column_name, aggregate_function(column_name) FROM table_name WHERE column_name operator value GROUP BY column_name SELECT column_name, aggregate_function(column_name) FROM table_name WHERE column_name operator value GROUP BY column_name HAVING aggregate_function(column_name) operator value SELECT column_name(s) FROM table_name WHERE column_name IN (value1,value2,..) INSERT INTO table_name
HAVING
IN
INSERT INTO
VALUES (value1, value2, value3,....) or INSERT INTO table_name (column1, column2, column3,...) VALUES (value1, value2, value3,....) INNER JOIN SELECT column_name(s) FROM table_name1 INNER JOIN table_name2 ON table_name1.column_name=table_name2.column_name SELECT column_name(s) FROM table_name1 LEFT JOIN table_name2 ON table_name1.column_name=table_name2.column_name SELECT column_name(s) FROM table_name1 RIGHT JOIN table_name2 ON table_name1.column_name=table_name2.column_name SELECT column_name(s) FROM table_name1 FULL JOIN table_name2 ON table_name1.column_name=table_name2.column_name SELECT column_name(s) FROM table_name WHERE column_name LIKE pattern SELECT column_name(s) FROM table_name ORDER BY column_name [ASC|DESC] SELECT column_name(s) FROM table_name SELECT * FROM table_name SELECT DISTINCT column_name(s)
LEFT JOIN
RIGHT JOIN
FULL JOIN
LIKE
ORDER BY
SELECT
SELECT *
SELECT DISTINCT
FROM table_name SELECT INTO SELECT * INTO new_table_name [IN externaldatabase] FROM old_table_name or SELECT column_name(s) INTO new_table_name [IN externaldatabase] FROM old_table_name SELECT TOP SELECT TOP number|percent column_name(s) FROM table_name TRUNCATE TABLE table_name SELECT column_name(s) FROM table_name1 UNION SELECT column_name(s) FROM table_name2 SELECT column_name(s) FROM table_name1 UNION ALL SELECT column_name(s) FROM table_name2 UPDATE table_name SET column1=value, column2=value,... WHERE some_column=some_value SELECT column_name(s) FROM table_name WHERE column_name operator value
UNION ALL
UPDATE
WHERE