SQL (Structured Query Language)
SQL (Structured Query Language)
1. What is SQL
3. What is RDBMS
RDBMS is the basis for SQL, and for all modern database systems like MS
SQL Server, IBM DB2, Oracle, MySQL, and Microsoft Access.
4. SQL Syantax
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.
Below is an example of a table called "Persons":
The table above contains three records (one for each person) and five
columns (P_Id, LastName, FirstName, Address, and City).
5. SQL Statements
Most of the actions you need to perform on a database are done with SQL
statements.
The following SQL statement will select all the records in the "Persons" table:
and
Now we want to select the content of the columns named "LastName" and
"FirstName" from the table above.
LastName FirstName
Hansen Ola
Svendson Tove
Pettersen Kari
The DISTINCT keyword can be used to return only distinct (different) values.
Now we want to select only the distinct values from the column named
"City" from the table above.
City
Sandnes
Stavanger
Now we want to select only the persons living in the city "Sandnes" from the
table above.
The OR operator displays a record if either the first condition or the second
condition is true.
AND Operator Example
The "Persons" table:
Now we want to select only the persons with the first name equal to "Tove"
AND the last name equal to "Svendson":
OR Operator Example
Now we want to select only the persons with the first name equal to "Tove"
OR the first name equal to "Ola":
Now we want to select only the persons with the last name equal to
"Svendson" AND the first name equal to "Tove" OR to "Ola":
If you want to sort the records in a descending order, you can use the DESC
keyword.
ORDER BY Example
The "Persons" table:
P_Id LastName FirstName Address City
Now we want to select all the persons from the table above, however, we
want to sort the persons by their last name.
The first form doesn't specify the column names where the data will be
inserted, only their values:
The second form specifies both the column names and the values to be
inserted:
Note: Notice the WHERE clause in the UPDATE syntax. The WHERE clause
specifies which record or records that should be updated. If you omit the
WHERE clause, all records will be updated!
SQL UPDATE Example
The "Persons" table:
5 Tjessem Jakob
Now we want to update the person "Tjessem, Jakob" in the "Persons" table.
UPDATE Persons
SET Address='Nissestien 67', City='Sandnes'
WHERE LastName='Tjessem' AND FirstName='Jakob'
UPDATE Persons
SET Address='Nissestien 67', City='Sandnes'
Note: Notice the WHERE clause in the DELETE syntax. The WHERE clause
specifies which record or records that should be deleted. If you omit the
WHERE clause, all records will be deleted!
Now we want to delete the person "Tjessem, Jakob" in the "Persons" table.
or
Note: Be very careful when deleting records. You cannot undo this
statement!
13. The TOP Clause
The TOP clause is used to specify the number of records to return.
The TOP clause can be very useful on large tables with thousands of records.
Returning a large number of records can impact on performance.
Example
SELECT *
FROM Persons
LIMIT 5
Oracle Syntax
SELECT column_name(s)
FROM table_name
WHERE ROWNUM <= number
Example
SELECT *
FROM Persons
WHERE ROWNUM <=5
SQL TOP Example
The "Persons" table:
Now we want to select only the two first records in the table above.
Now we want to select only 50% of the records in the table above.
The "%" sign can be used to define wildcards (missing letters in the
pattern) both before and after the pattern.
Next, we want to select the persons living in a city that ends with an "s"
from the "Persons" table.
Next, we want to select the persons living in a city that contains the pattern
"tav" from the "Persons" table.
It is also possible to select the persons living in a city that NOT contains the
pattern "tav" from the "Persons" table, by using the NOT keyword.
Wildcard Description
% A substitute for zero or more characters
_ A substitute for exactly one character
[charlist] Any single character in charlist
[^charlist] Any single character not in charlist
or
[!charlist]
Next, we want to select the persons living in a city that contains the pattern
"nes" from the "Persons" table.
Next, we want to select the persons with a last name that starts with "S",
followed by any character, followed by "end", followed by any character,
followed by "on" from the "Persons" table.
Next, we want to select the persons with a last name that do not start with
"b" or "s" or "p" from the "Persons" table.
SQL IN Syntax
SELECT column_name(s)
FROM table_name
WHERE column_name IN (value1,value2,...)
IN Operator Example
The "Persons" table:
Now we want to select the persons with a last name equal to "Hansen" or
"Pettersen" from the table above.
Now we want to select the persons with a last name alphabetically between
"Hansen" and "Pettersen" from the table above.
Example 2
To display the persons outside the range in the previous example, use NOT
BETWEEN:
SELECT * FROM Persons
WHERE LastName
NOT BETWEEN 'Hansen' AND 'Pettersen'
Alias Example
Assume we have a table called "Persons" and another table called
"Product_Orders". We will give the table aliases of "p" and "po" respectively.
Now we want to list all the orders that "Ola Hansen" is responsible for.
As you'll see from the two SELECT statements above; aliases can make
queries easier to both write and to read.
Note that the "P_Id" column is the primary key in the "Persons" table. This
means that no two rows can have the same P_Id. The P_Id distinguishes
two persons even if they have the same name.
Next, we have the "Orders" table:
Note that the "O_Id" column is the primary key in the "Orders" table and
that the "P_Id" column refers to the persons in the "Persons" table without
using their names.
Notice that the relationship between the two tables above is the "P_Id"
column.
• JOIN: Return rows when there is at least one match in both tables
• LEFT JOIN: Return all rows from the left table, even if there are no
matches in the right table
• RIGHT JOIN: Return all rows from the right table, even if there are
no matches in the left table
• FULL JOIN: Return rows when there is a match in one of the tables
1 77895 3
2 44678 3
3 22456 1
4 24562 1
5 34764 15
The INNER JOIN keyword return rows when there is at least one match in
both tables. If there are rows in "Persons" that do not have matches in
"Orders", those rows will NOT be listed.
1 77895 3
2 44678 3
3 22456 1
4 24562 1
5 34764 15
Now we want to list all the persons and their orders - if any, from the tables
above.
Svendson Tove
The LEFT JOIN keyword returns all the rows from the left table (Persons),
even if there are no matches in the right table (Orders).
1 77895 3
2 44678 3
3 22456 1
4 24562 1
5 34764 15
Now we want to list all the orders with containing persons - if any, from the
tables above.
34764
The RIGHT JOIN keyword returns all the rows from the right table (Orders),
even if there are no matches in the left table (Persons).
1 77895 3
2 44678 3
3 22456 1
4 24562 1
5 34764 15
Now we want to list all the persons and their orders, and all the orders with
their persons.
34764
The FULL JOIN keyword returns all the rows from the left table (Persons),
and all the rows from the right table (Orders). If there are rows in "Persons"
that do not have matches in "Orders", or if there are rows in "Orders" that
do not have matches in "Persons", those rows will be listed as well.
Notice that each SELECT statement within the UNION must have the same
number of columns. The columns must also have similar data types. Also,
the columns in each SELECT statement must be in the same order.
Note: The UNION operator selects only distinct values by default. To allow
duplicate values, use UNION ALL.
PS: The column names in the result-set of a UNION are always equal to the
column names in the first SELECT statement in the UNION.
"Employees_Norway":
E_ID E_Name
01 Hansen, Ola
02 Svendson, Tove
03 Svendson, Stephen
04 Pettersen, Kari
"Employees_USA":
E_ID E_Name
01 Turner, Sally
02 Kent, Clark
03 Svendson, Stephen
04 Scott, Stephen
Now we want to list all the different employees in Norway and USA.
E_Name
Hansen, Ola
Svendson, Tove
Svendson, Stephen
Pettersen, Kari
Turner, Sally
Kent, Clark
Scott, Stephen
Note: This command cannot be used to list all employees in Norway and
USA. In the example above we have two employees with equal names, and
only one of them will be listed. The UNION command selects only distinct
values.
Result
E_Name
Hansen, Ola
Svendson, Tove
Svendson, Stephen
Pettersen, Kari
Turner, Sally
Kent, Clark
Svendson, Stephen
Scott, Stephen
The data type specifies what type of data the column can hold. For a
complete reference of all the data types available in MS Access, MySQL, and
SQL Server, go to our complete Data Types reference.
The P_Id column is of type int and will hold a number. The LastName,
FirstName, Address, and City columns are of type varchar with a maximum
length of 255 characters.
The empty table can be filled with data with the INSERT INTO statement.
22. SQL Constraints
Constraints are used to limit the type of data that can go into a table.
Constraints can be specified when a table is created (with the CREATE TABLE
statement) or after the table is created (with the ALTER TABLE statement).
• NOT NULL
• UNIQUE
• PRIMARY KEY
• FOREIGN KEY
• CHECK
• DEFAULT
The NOT NULL constraint enforces a field to always contain a value. This
means that you cannot insert a new record, or update a record without
adding a value to this field.
The following SQL enforces the "P_Id" column and the "LastName" column to
not accept NULL values:
The UNIQUE and PRIMARY KEY constraints both provide a guarantee for
uniqueness for a column or set of columns.
Note that you can have many UNIQUE constraints per table, but only one
PRIMARY KEY constraint per table.
MySQL:
MySQL:
Each table should have a primary key, and each table can have only ONE
primary key.
MySQL:
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).
Note: If you use the ALTER TABLE statement to add a primary key, the
primary key column(s) must already have been declared to not contain NULL
values (when the table was first created).
To DROP a PRIMARY KEY Constraint
To drop a PRIMARY KEY constraint, use the following SQL:
MySQL:
Let's illustrate the foreign key with an example. Look at the following two
tables:
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 that invalid data form being
inserted into the foreign key column, because it has to be one of the values
contained in the table it points to.
MySQL:
MySQL:
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.
My SQL:
The default value will be added to all new records, if no other value is
specified.
The DEFAULT constraint can also be used to insert system values, by using
functions like GETDATE():
MySQL:
ALTER TABLE Persons
ALTER City SET DEFAULT 'SANDNES'
MySQL: