0% found this document useful (0 votes)
5 views

SQL

The document provides an overview of SQL joins, constraints, and advanced SQL concepts. It details various types of joins (INNER, LEFT, RIGHT, FULL, SELF, and CARTESIAN), their syntax, and examples, as well as explaining constraints such as domain integrity, entity integrity, and referential integrity. Additionally, it covers how to create, modify, and drop constraints in SQL, including NOT NULL, CHECK, UNIQUE, PRIMARY KEY, and FOREIGN KEY constraints.

Uploaded by

Vidhya
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views

SQL

The document provides an overview of SQL joins, constraints, and advanced SQL concepts. It details various types of joins (INNER, LEFT, RIGHT, FULL, SELF, and CARTESIAN), their syntax, and examples, as well as explaining constraints such as domain integrity, entity integrity, and referential integrity. Additionally, it covers how to create, modify, and drop constraints in SQL, including NOT NULL, CHECK, UNIQUE, PRIMARY KEY, and FOREIGN KEY constraints.

Uploaded by

Vidhya
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 14

Joins, Constraints and Advanced SQL

JOINS
The SQL Joins clause is used to combine records from two or more tables in a database.
A JOIN is a means for combining fields from two tables by using values common to each.

The Syntax for joining two tables is:


SELECT col1, col2, col3...
FROM table_name1, table_name2
WHERE table_name1.col2 = table_name2.col1;
Consider the following two tables;
(a) CUSTOMER and the values in the CUSTOMER table is as follows:

Customer table

(b) Another table is ORDERS and its values are as follows:


Now, let us join these two tables in our SELECT statement as follows:
SQL> SELECT ID, NAME, AGE, AMOUNT
FROM CUSTOMERS, ORDERS
WHERE CUSTOMERS.ID = ORDERS.CUSTOMER_ID;
This would produce the following result:

Join Operation

Here, it is noticeable that the join is performed in the WHERE clause. Several operators can be
used to join tables, such as =, <, >, <>, <=, >=, !=, BETWEEN, LIKE, and NOT; they can all be used
to join tables. However, the most common operator is the equal symbol.

JOINS TYPES
There are different types of joins available in SQL:
 INNER JOIN: returns rows when there is a match in both tables.
 LEFT JOIN: returns all rows from the left table, even if there are no matches in the right table.
Joins, Constraints and Advanced SQL 1.3

 RIGHT JOIN: returns all rows from the right table, even if there are no matches in the left
table.
 FULL JOIN: returns rows when there is a match in one of the tables.
 SELF JOIN: is used to join a table to itself as if the table were two tables, temporarily
renaming at least one table in the SQL statement.
 CARTESIAN JOIN: returns the Cartesian product of the sets of records from the two or more
joined tables.
INNER JOIN
The most commonly used and important of the joins is the INNER JOIN. It is also referred to
as an EQUIJOIN. The INNER JOIN creates a new result table by combining column values of two
tables based upon the join-condition. The query compares each row of the first table with each row of
second table to be joint together to find all pairs of rows which satisfy the join-condition. When the
join-condition is satisfied, column values for each matched pair of rows of A and B are combined into
a result row.
Syntax:
The basic syntax of INNER JOIN is as follows:
SELECT table1.column1, table2.column2...
FROM table1
INNER JOIN table2
ON table1.common_filed = table2.common_field;

Now, let us join these two tables using INNER JOIN as follows:

SQL> SELECT ID, NAME, AMOUNT, DATE_OF_ORDER


FROM CUSTOMER
INNER JOIN ORDERS
ON CUSTOMER.ID = ORDERS.CUSTOMER_ID

Inner Join operation

LEFT JOIN
The SQL LEFT JOIN returns all rows from the left table, even if there are no matches in the
right table. This means that a left join returns all the values from the left table, plus matched values
from the right table or NULL in case of no matching join condition.
Syntax:
The basic syntax of LEFT JOIN is as follows:
SELECT table1.column1, table2.column2...
FROM table1
LEFT JOIN table2
ON table1.common_filed = table2.common_field;
Consider the following example
SQL> SELECT ID, NAME, AMOUNT, DATE_OF_ORDER
FROM CUSTOMER
LEFT JOIN ORDERS
ON CUSTOMER.ID = ORDERS.CUSTOMER_ID;

Left Join operation

RIGHT JOIN
The SQL RIGHT JOIN returns all rows from the right table, even if there are no matches in
the left table. This means that a right join returns all the values from the right table, plus matched
values from the left table or NULL in case of no matching join condition.
Syntax:
The basic syntax of RIGHT JOIN is as follows:
SELECT table1.column1, table2.column2...
FROM table1
RIGHT JOIN table2
ON table1.common_filed = table2.common_field;
Consider the following example
SQL> SELECT ID, NAME, AMOUNT, DATE_OF_ORDER
FROM CUSTOMER
RIGHT JOIN ORDERS
Joins, Constraints and Advanced SQL 1.5

ON CUSTOMER.ID = ORDERS.CUSTOMER_ID;

Right Join operation

FULL JOIN
The SQL FULL JOIN combines the results of both left and right outer joins. The joined table
will contain all records from both tables, and fill in NULLs for missing matches on either side.
Syntax:
The basic syntax of FULL JOIN is as follows:
SELECT table1.column1, table2.column2...
FROM table1
FULL JOIN table2
ON table1.common_filed = table2.common_field;
Consider the following example
SQL> SELECT ID, NAME, AMOUNT, DATE_OF_ORDER
FROM CUSTOMER
FULL JOIN ORDERS
ON CUSTOMER.ID = ORDERS.CUSTOMER_ID;

Full Join operation


SELF JOIN
The SQL SELF JOIN is used to join a table to itself as if the table were two tables,
temporarily renaming at least one table in the SQL statement.
Syntax:
The basic syntax of SELF JOIN is as follows:
SELECT a.column_name, b.column_name...
FROM table1 a, table1 b
WHERE a.common_filed = b.common_field;
Here, WHERE clause could be any given expression based on your requirement.
Consider the following example
SQL> SELECT a.ID, b.NAME, a.SALARY
FROM CUSTOMER a, CUSTOMER b
WHERE a.SALARY < b.SALARY;

Self Join operation

CARTESIAN JOIN
The CARTESIAN JOIN or CROSS JOIN returns the Cartesian product of the sets of records
from the two or more joined tables. Thus, it equates to an inner join where the join-condition always
evaluates to True or where the join-condition is absent from the statement.
Syntax:
Joins, Constraints and Advanced SQL 1.7

The basic syntax of INNER JOIN is as follows:


SELECT table1.column1, table2.column2...
FROM table1, table2 [, table3 ]
Consider the following example
SQL> SELECT ID, NAME, AMOUNT, DATE_OF_ORDER
FROM CUSTOMER, ORDERS;

Cartesian Join operation


CONSTRAINTS
Constraints are used to specify rules for the data in a table. Before one can start to implement the
database tables, one must define the integrity constraints. Integrity means something like 'be right' and
consistent. This constraint ensures whether the data in a database is right and is in good condition.
Constraints also provide mechanism to prevent invalid data entry in the table and accidental damages
to the databases.
Constraints can be defined in two ways
1. The constraints can be specified immediately after the column definition. This is called
column-level definition. i.e., constraints specified when the table is created (inside the create
table statement)
2. The constraints can be specified after all the columns are defined. This is called table-level
definition. i.e., after the table is created (inside the alter table statement)
GENERAL SYNTAX FOR CREATING CONSTRAINTS
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,
....
);
Dropping Constraints:
Any constraint that you have defined can be dropped using the ALTER TABLE command
with the DROP CONSTRAINT option.
Syntax:
ALTER TABLE TABLE_NAME DROP CONSTRAINT CONSTRAINT_NAME;

TYPES OF CONSTRAINTS
The constraints falls under three different categories
1. Domain integrity Constraints
2. Entity integrity Constraints
3. Referential integrity Constraints

DOMAIN INTEGRITY CONSTRAINTS


A domain is a set of values that may be assigned to an attribute. All values that appear in a
column of a relation (table) must be taken from the same domain. Domain restricts the values of
attributes in the relation and it is a constraint of the relational model. We need more specific ways to
state what data values are not allowed and what format is suitable for an attributes. The SQL
constraints that fall under this category are
 Not null - indicates that a column cannot store null value
 Check - ensures that the value in a column meets a specific condition

NOT NULL CONSTRAINTS


By default, a column can hold NULL values. If we do not want a column to have a NULL
value, then we have to define NOT NULL constraint on that particular column or columns. This
Joins, Constraints and Advanced SQL 1.9

constraint will not allow NULL values for the specified column. A NULL is not the same as no data,
rather, it represents unknown data.
Syntax to define a Not Null constraint:
CREATE TABLE <TABLE NAME>(COLUMNNAME DATA TYPE (SIZE)
CONSTRAINT CONSTRAINT_NAME NOT NULL);

Example:
For example, the following SQL creates a new table called CUSTOMERS and adds five
columns, three of which, ID and NAME and AGE, specify not to accept NULLs:
CREATE TABLE CUSTOMERS (
ID INT NOT NULL,
NAME VARCHAR (20) NOT NULL,
AGE INT NOT NULL,
ADDRESS CHAR (25),
SALARY DECIMAL (18, 2),
KEY (ID)
);
If CUSTOMERS table has already been created, then to add a NOT NULL constraint to
SALARY column, the following statement is used:
ALTER TABLE CUSTOMERS
MODIFY SALARY DECIMAL (18, 2) NOT NULL;
CHECK CONSTRAINTS
The CHECK Constraint enables a condition to check the value being entered into a record. If
the condition evaluates to false, the record violates the constraint and isn't entered into the table.
Syntax to define a Check constraint:
CREATE TABLE <TABLE NAME>(COLUMNNAME DATA TYPE (SIZE) CONSTRAINT
CONSTRAINT_NAME CHECK (CHECK_CONDITION));
Example:
For example, the following SQL creates a new table called CUSTOMERS and adds five columns.
Here, we add a CHECK with AGE column, so that you cannot have any CUSTOMER below 18 years:
CREATE TABLE CUSTOMERS (
ID INT NOT NULL,
NAME VARCHAR (20) NOT NULL,
AGE INT NOT NULL CHECK (AGE >= 18),
ADDRESS CHAR (25),
SALARY DECIMAL (18, 2),
KEY (ID)
);
If CUSTOMERS table has already been created, then to add a CHECK constraint to AGE
column, you would write a statement similar to the following:
ALTER TABLE CUSTOMERS
MODIFY AGE INT NOT NULL CHECK (AGE >= 18);
You can also use following syntax, which supports naming the constraint in multiple columns as well:
ALTER TABLE CUSTOMERS
ADD CONSTRAINT myCheckConstraint CHECK (AGE >= 18);
DROP a CHECK Constraint:
To drop a CHECK constraint, use the following SQL.
ALTER TABLE CUSTOMERS
DROP CONSTRAINT myCheckConstraint;

ENTITY INTEGRITY CONSTRAINTS


The entity integrity constraints state that no primary key value can be null. This is because the
primary key value is used to identify individual tuples in a relation. The SQL constraints that fall under
this category are
 Unique - ensures that each row must have a unique value
 Primary key - a combination of a not null and unique.
UNIQUE CONSTRAINTS
This constraint ensures that a column or a group of columns in each row have a distinct value. A
column(s) can have a null value but the values cannot be duplicated.
Syntax for unique constraints:
CREATE TABLE <TABLE NAME>(COLUMNNAME DATA TYPE (SIZE)
CONSTRAINT CONSTRAINT_NAME UNIQUE);
Assigning unique constraints for multiple columns is called composite unique constraints. The
syntax is as follows
CREATE TABLE <TABLE NAME>(COLUMNNAME1 DATA TYPE (SIZE),
COLUMNNAME2 DATA TYPE (SIZE), CONSTRAINT CONSTRAINT_NAME
UNIQUE (COLUMNNAME1, COLUMNNAME2));
Example:
For example, the following statement creates a new table called customers and adds five
columns. Here, age column is set to unique, so that you cannot have two records with same age:
CREATE TABLE CUSTOMERS(
ID INT NOT NULL,
NAME VARCHAR (20) NOT NULL,
AGE INT NOT NULL UNIQUE,
ADDRESS CHAR (25) ,
SALARY DECIMAL (18, 2),
KEY (ID)
);
If customers table has already been created, then to add a unique constraint to age column,
you would write a statement similar to the following:
ALTER TABLE CUSTOMERS
MODIFY AGE INT NOT NULL UNIQUE;
You can also use following syntax, which supports naming the constraint in multiple columns as well:
ALTER TABLE CUSTOMERS
Joins, Constraints and Advanced SQL 1.11

ADD CONSTRAINT MYUNIQUECONSTRAINT UNIQUE(AGE, SALARY);


Drop a unique constraint:
To drop a unique constraint, use the following statement:
ALTER TABLE CUSTOMERS
DROP CONSTRAINT MYUNIQUECONSTRAINT;

PRIMARY KEY CONSTRAINTS


A primary key is a field in a table which uniquely identifies each row/record in a database
table. Primary keys must contain unique values. A primary key column cannot have NULL values. A
table can have only one primary key, which may consist of single or multiple fields. When multiple
fields are used as a primary key, they are called a composite key.
Syntax for primary key constraints
CREATE TABLE <TABLE NAME>(COLUMNNAME DATA TYPE (SIZE)
CONSTRAINT CONSTRAINT_NAME PRIMARY KEY);
Composite primary key
CREATE TABLE <TABLE NAME>(COLUMNNAME1 DATA TYPE (SIZE),
COLUMNNAME2 DATA TYPE (SIZE), CONSTRAINT CONSTRAINT_NAME
PRIMARY KEY (COLUMNNAME1, COLUMNNAME2));

Create Primary Key:


Here is the syntax to define ID attribute as a primary key in a CUSTOMERS table.
CREATE TABLE CUSTOMERS(
ID INT NOT NULL,
NAME VARCHAR (20) NOT NULL,
AGE INT NOT NULL,
ADDRESS CHAR (25) ,
SALARY DECIMAL (18, 2),
PRIMARY KEY (ID)
);
To create a PRIMARY KEY constraint on the "ID" column when CUSTOMERS table
already exists, use the following SQL syntax:
ALTER TABLE CUSTOMER ADD PRIMARY KEY (ID);

To use ALTER TABLE statement to add a primary key to an already existing table, the
column to which the primary key is to be assigned should have NOT NULL constraint when the table
was first created. If null values are present then primary key cannot be assigned.
For defining a PRIMARY KEY constraint on multiple columns, use the following SQL
statement:
CREATE TABLE CUSTOMERS(
ID INT NOT NULL,
NAME VARCHAR (20) NOT NULL,
AGE INT NOT NULL,
ADDRESS CHAR (25) ,
SALARY DECIMAL (18, 2),
PRIMARY KEY (ID, NAME)
);
To create a PRIMARY KEY constraint on the "ID" and "NAMES" columns when
CUSTOMERS table already exists, use the following SQL syntax:
ALTER TABLE CUSTOMERS
ADD CONSTRAINT PK_CUSTID PRIMARY KEY (ID, NAME);
Delete Primary Key:
To remove the primary key constraint uses the following syntax:
ALTER TABLE CUSTOMERS DROP PRIMARY KEY;

REFERENTIAL INTEGRITY CONSTRAINTS


Ensures that a value appears in one relation for a given set of attributes also appears for a
certain set of attributes in another relation. This condition is called referential integrity
Reference key (foreign key) – Its represent relationships between tables. Foreign key is a column
whose values are derived from the primary key of the same or some other table.
The referential integrity constraint is specified between two tables and it is used to maintain
the consistency among rows between the two tables.
The rules are:
1. Deleting a record from a primary table is not possible if matching records exist in a related
table.
2. Change a primary key value in the primary table is not possible if that record has related
records.
3. Entering a value in the foreign key field of the related table is not possible if it that doesn't
exist in the primary key of the primary table.
4. However, entering a Null value in the foreign key is possible, specifying that the records are
unrelated.
FOREIGN KEY CONSTRAINTS
Foreign Key is a column or a combination of columns whose values match a Primary Key in a
different table. The relationship between 2 tables matches the Primary Key in one of the tables with a
Foreign Key in the second table. If a table has a primary key defined on any field(s), then you cannot
have two records having the same value of that field(s).
Syntax:
CREATE TABLE <TABLE NAME>(COLUMNNAME DATA TYPE (SIZE) CONSTRAINT
CONSTRAINT_NAME REFERENCES PARENT_TABLE_NAME);

Example:
Consider the structure of the two tables as follows:
CUSTOMERS table:
CREATE TABLE CUSTOMERS(
ID INT NOT NULL,
NAME VARCHAR (20) NOT NULL,
Joins, Constraints and Advanced SQL 1.13

AGE INT NOT NULL,


ADDRESS CHAR (25) ,
SALARY DECIMAL (18, 2),
PRIMARY KEY (ID)
);
ORDERS table:
CREATE TABLE ORDERS (
ID INT NOT NULL,
DATE DATETIME,
CUSTOMER_ID INT references CUSTOMERS(ID),
AMOUNT double,
PRIMARY KEY (ID)
);
If ORDERS table has already been created, and the foreign key has not yet been set, use the
syntax for specifying a foreign key by altering a table.
ALTER TABLE ORDERS
ADD FOREIGN KEY (Customer_ID) REFERENCES CUSTOMERS (ID);
DROP a FOREIGN KEY Constraint:
To drop a FOREIGN KEY constraint, use the following syntax:
ALTER TABLE ORDERS
DROP FOREIGN KEY;
INDEX CONSTRAINT
The INDEX is used to create and retrieve data from the database very quickly. Index can be
created by using single or group of columns in a table. When index is created, it is assigned a ROWID
for each row before it sorts out the data.
Proper indexes are good for performance in large databases, but you need to be careful while creating
index. Selection of fields depends on what you are using in your SQL queries.
Example:
For example, the following SQL creates a new table called CUSTOMERS and adds five
columns:
CREATE TABLE CUSTOMERS(
ID INT NOT NULL,
NAME VARCHAR (20) NOT NULL,
AGE INT NOT NULL,
ADDRESS CHAR (25) ,
SALARY DECIMAL (18, 2),
PRIMARY KEY (ID)
);
Now, you can create index on single or multiple columns using the following syntax:
CREATE INDEX index_name
ON table_name ( column1, column2.....);
To create an INDEX on AGE column, to optimize the search on customers for a particular age,
following is the SQL syntax:
CREATE INDEX idx_age
ON CUSTOMERS ( AGE );
DROP an INDEX Constraint:
To drop an INDEX constraint, use the following syntax:
ALTER TABLE CUSTOMERS
DROP INDEX idx_age;
DEFAULT CONSTRAINT
The DEFAULT constraint provides a default value to a column when the INSERT INTO
statement does not provide a specific value.
Example:
For example, the following SQL creates a new table called CUSTOMERS and adds five
columns. Here, SALARY column is set to 5000.00 by default, so in case INSERT INTO statement
does not provide a value for this column, then by default this column would be set to 5000.00.
CREATE TABLE CUSTOMERS(
ID INT NOT NULL,
NAME VARCHAR (20) NOT NULL,
AGE INT NOT NULL,
ADDRESS CHAR (25) ,
SALARY DECIMAL (18, 2) DEFAULT 5000.00,
PRIMARY KEY (ID)
);
If CUSTOMERS table has already been created, then to add a DFAULT constraint to
SALARY column, you would write a statement similar to the following:
ALTER TABLE CUSTOMERS
MODIFY SALARY DECIMAL (18, 2) DEFAULT 5000.00;
Drop Default Constraint:
To drop a DEFAULT constraint, use the following syntax:
ALTER TABLE CUSTOMERS
ALTER COLUMN SALARY DROP DEFAULT;

You might also like