Databaselab 6
Databaselab 6
ENGINEERING
LAB ASSESSMENT:
Ability to Conduct
Experiment
Data presentation
Experimental results
Conclusion
Objective:
Understand the different commands and constrains used in SQL.
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.
SQL UNION Example:
Look at the following tables:
"Employees_Norway":
"Employees_USA":
Now we want to list all the different employees in Norway and USA. We use the following
SELECT statement:
The result-set will look like this:
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:
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).
We will focus on the following constraints:
• NOT NULL
• UNIQUE
• PRIMARY KEY
• FOREIGN KEY
• CHECK
• DEFAULT
To allow naming of a UNIQUE constraint, and for defining a UNIQUE constraint on multiple
columns, use the following SQL syntax:
MySQL:
MySQL:
To allow naming of a FOREIGN KEY constraint, and for defining a FOREIGN KEY constraint on
multiple columns, use the following SQL syntax:
SQL FOREIGN KEY Constraint on ALTER TABLE:
To create a FOREIGN KEY constraint on the "P_Id" column when the "Orders" table is already
created, use the following SQL:
To allow naming of a FOREIGN KEY constraint, and for defining a FOREIGN KEY constraint on
multiple columns, use the following SQL syntax:
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.
To allow naming of a CHECK constraint, and for defining a CHECK constraint on multiple
columns, use the following SQL syntax:
To allow naming of a CHECK constraint, and for defining a CHECK constraint on multiple
columns, use the following SQL syntax:
The DEFAULT constraint can also be used to insert system values, by using functions like
GETDATE():
Note: The syntax for creating indexes varies amongst different databases. Therefore: Check
the syntax for creating indexes in your database.
If you want to create an index on a combination of columns, you can list the column names
within the parentheses, separated by commas:
Lab Tasks:
In lab Tasks: