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

7 Structured Query Language

The document provides an overview of Structured Query Language (SQL), detailing its purpose as a means to interact with relational databases for tasks such as data retrieval, manipulation, and storage. It covers SQL commands categorized into Data Definition Language (DDL), Data Manipulation Language (DML), Data Control Language (DCL), and Data Query Language (DQL), along with examples and explanations of SQL queries and constraints. Additionally, it introduces tools for writing SQL and discusses the structure of database tables, including fields, records, and various SQL clauses.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views

7 Structured Query Language

The document provides an overview of Structured Query Language (SQL), detailing its purpose as a means to interact with relational databases for tasks such as data retrieval, manipulation, and storage. It covers SQL commands categorized into Data Definition Language (DDL), Data Manipulation Language (DML), Data Control Language (DCL), and Data Query Language (DQL), along with examples and explanations of SQL queries and constraints. Additionally, it introduces tools for writing SQL and discusses the structure of database tables, including fields, records, and various SQL clauses.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 69

Fundamentals of Database Systems

Chapter 7: Structured Query Language

05/26/2025 Fundamentals of Database Systems 1


Introduction to SQL
 SQL is an abbreviation for structured query language.
 It is a language used to perform action such as update, retrieve,
manipulate and store data on relational database.
 It is a means for communicating with the database.
 SQL is just a query language, it is not a database.
 It is a query language that is standardized by the American
National Standards Institute (ANSI) to operate databases.
 It is pronounced as S-Q-L or sometime See-Qwell.

05/26/2025 Fundamentals of Database Systems 2


Facts about SQL
 It was developed at IBM by Donald D. Chamberlin and Raymond
Boyce in the early 1970s. It was initially called SEQUEL (Structured
English QUEry Language).
 SQL is a powerful language which means it uses very simple English
sentences and also uses very few lines. It uses common words such
as SELECT, INSERT, UPDATE and many more to perform its core
functionalities.
 SQL is declarative language which means when you write a query
you have to describe what needs to be done.
 All relational database management systems like MySQL, MS
Access, Oracle, Sybase, Informix, postgres and SQL Server use SQL
as standard database language.
05/26/2025 Fundamentals of Database Systems 3
Why SQL?
 Allows users to access data in relational database management systems.
 Allows users to describe the data.
 Allows users to define the data in database and manipulate that data.
 Allows to embed within other languages using SQL modules, libraries & pre-compilers.
 Allows users to create and drop databases and tables.
 Allows users to create view, stored procedure, functions in a database.
 Allows users to set permissions on tables, procedures and views
 SQL is an ANSI standard computer language
 SQL can execute queries against a database
 SQL can retrieve data from a database
 SQL can insert new records in a database
 SQL can delete records from a database
 SQL can update records in a database
 SQL is easy to learn
05/26/2025 Fundamentals of Database Systems 4
What SQL does?
 With SQL, we can query our database in a numbers of ways, using
English-like statements.
 With SQL, user can access data from relational database
management system.
 It allows user to describe the data.
 It allows user to define the data in database and manipulate it
when needed.
 It allows user to create and drop database and table.
 It allows user to create view, stored procedure, function in a
database.
 It allows user to set permission on tables, procedure and view.
05/26/2025 Fundamentals of Database Systems 5
SQL Commands
 The standard SQL commands to interact with relational
databases are CREATE, SELECT, INSERT, UPDATE, DELETE and
DROP.
 These commands can be classified into groups based on their
nature:
DDL -Data Definition Language:
Command Description
CREATE Creates a new table, a view of a table, or other
object in database
ALTER Modifies an existing database object, such as a
table.
DROP Deletes an entire table, a view of a table or other
object in the database.

05/26/2025 Fundamentals of Database Systems 6


SQL Commands…

DML -Data Manipulation Language:

Command Description
INSERT Creates a record
DELETE Deletes records
UPDATE Modifies records

05/26/2025 Fundamentals of Database Systems 7


SQL Commands…
 DCL -Data Control Language
Command Description
GRANT Gives a privilege to user

REVOKE Takes back privileges granted from user


Remove a previously granted or denied
permission

 DQL -Data Query Language


Command Description
Retrieves certain records from
SELECT one or more tables

05/26/2025 Fundamentals of Database Systems 8


Tools to write SQL
 SQL Server Management Studio(SSMS)
 SQL Developer
 SQL Workbench

05/26/2025 Fundamentals of Database Systems 9


SQL Server Management Studio (SSMS)
 SQL Server Management Studio is a workstation or a client tool which is used
to connect to and manage your SQL Server.
 It allows DBAs and database developers to configure, manage, and
administer all components within SQL Server.
 Its main functionality is to create databases and tables, execute SQL queries
for inserting, updating, and deleting data, creating and managing stored
procedures, triggers, views, and cursors.
 It also enables us to set privileges (securities) on databases and their objects.
 Here we put the links to download both SQL server and SSMS individually. So,
the links are below respectively
 https://www.microsoft.com/en-us/download/details.aspx?id=42299
 https://docs.microsoft.com/en-us/sql/ssms/download-sql-server-managemen
t-studio-ssms?view=sql-server-ver15
05/26/2025 Fundamentals of Database Systems 10
SQL Database Tables
 What is table?
 The data in RDBMS is stored in database objects called tables.
The table is a collection of related data entries and it consists of
columns and rows.
 Remember, a table is the most common and simplest form of
data storage in a relational database. Following is the example of
a CUSTOMERS table:

05/26/2025 Fundamentals of Database Systems 11


SQL Database Tables>>Example

05/26/2025 Fundamentals of Database Systems 12


SQL Database Tables>>field
 Every table is broken up into smaller entities called fields. The
fields in the CUSTOMERS table consist of ID, NAME, AGE,
ADDRESS and SALARY.
 A field is a column in a table that is designed to maintain specific
information about every record in the table.
What is record or row?

05/26/2025 Fundamentals of Database Systems 13


SQL Database Tables>> record or row
 A record, also called a row of data, is each individual entry that exists in a
table. For example, there are 7 records in the above CUSTOMERS table.
Following is a single row of data or record in the CUSTOMERS table:

What is NULL value?


 A NULL value in a table is a value in a field that appears to be blank, which
means a field with a NULL value is a field with no value.
 It is very important to understand that a NULL value is different than a
zero value or a field that contains spaces. A field with a NULL value is one
that has been left blank during record creation.
05/26/2025 Fundamentals of Database Systems 14
SQL Database Tables>> column
 A column is a vertical entity in a table that contains all
information associated with a specific field in a table.
 For example, a column in the CUSTOMERS table is ADDRESS,
which represents location description and would consist of the
following:

05/26/2025 Fundamentals of Database Systems 15


SQL Queries
 All the SQL statements start with any of the keywords like SELECT,
INSERT, UPDATE, DELETE, ALTER, DROP, CREATE, USE, SHOW and
all the statements end with a semicolon (;).
 Important point to be noted is that SQL is case insensitive, which
means SELECT and select have the same meaning in SQL
statements, but MySQL makes difference in table names.
 So if you are working with MySQL, then you need to give table
names as they exist in the database.

05/26/2025 Fundamentals of Database Systems 16


SQL Constraints
 Constraints are the rules enforced on data columns on table. These are
used to limit the type of data that can go into a table. This ensures the
accuracy and reliability of the data in the database.
 Following are commonly used constraints available in SQL:
 NOT NULL Constraint: Ensures that a column cannot have NULL value.
 DEFAULT Constraint: Provides a default value for a column when none is
specified.
 UNIQUE Constraint: Ensures that all values in a column are different.
 PRIMARY Key: Uniquely identified each rows/records in a database table.
 FOREIGN Key: Uniquely identified a rows/records in any another database table.
 CHECK Constraint: The CHECK constraint ensures that all values in a column
satisfy certain conditions.
 INDEX: Use to create and retrieve data from the database very quickly.
05/26/2025 Fundamentals of Database Systems 17
SQL Queries
SQL CREATE DATABASE Statement:
CREATE DATABASE database_name;

 The following SQL statement creates a database called "testDB":


CREATE DATABASE testDB;

SQL USE Statement:


USE database_name;

USE testDB;

05/26/2025 Fundamentals of Database Systems 18


SQL Queries
The SQL CREATE TABLE Statement
 The CREATE TABLE statement is used to create a new table in a database.
Syntax: CREATE TABLE table_name (
column1 datatype,
column2 datatype,
column3 datatype,
....
PRIMARY KEY( one or more columns )
);
 example demonstrates how you can create a table named "Person", with five columns. The column names will be
"LastName", "FirstName", "Address", and "Age":
CREATE TABLE Persons (
PersonID int,
LastName varchar(255),
FirstName varchar(255),
Address varchar(255),
City varchar(255)
);
05/26/2025 Fundamentals of Database Systems 19
Example
CREATE TABLE CUSTOMERS(
ID INT NOT NULL,
NAME VARCHAR (20) NOT NULL,
AGE INT NOT NULL CHECK (AGE >= 18),
ADDRESS CHAR (25) ,
SALARY DECIMAL (8, 2),
PRIMARY KEY (ID)
);

05/26/2025 Fundamentals of Database Systems 20


SQL Queries …
SQL INSERTINTO Statement:
INSERT INTO table_name( column1, column2....columnN)
VALUES ( value1, value2....valueN);

 Here, column1, column2,...columnN are the names of the


columns in the table into which you want to insert data.
 You may not need to specify the column(s) name in the SQL
query if you are adding values for all the columns of the table.
But make sure the order of the values is in the same order as the
columns in the table.

05/26/2025 Fundamentals of Database Systems 21


SQL Queries …
 INSERT INTO
CUSTOMERS(ID,NAME,AGE,ADDRESS,SALARY)VALUES(127,'Melaku',23,'DB
U',12305),(128,'Abebe',30,'DBU',5070);
When the above program executed the following message is
displayed

05/26/2025 Fundamentals of Database Systems 22


SQL Queries …
 SQL SELECT Statement SQL WHERE Clause
SELECT column1, column2....columnN
FROM table_name; SELECT column1, column2....columnN
FROM table_name
WHERE column_name IN (val-1, val-2,...val-N);
SELECT ID,NAME,AGE,ADDRESS,
SELECT * FROM CUSTOMERS WHERE ID=123;
SALARY FROM CUSTOMERS;
SELECT * FROM CUSTOMERS; Gives a result set like this:

Gives a result set like this:

05/26/2025 Fundamentals of Database Systems 23


SQL Queries …
SQL DISTINCT Clause SQL AND/OR/NOT Clause
SELECT DISTINCT column1, SELECT column1, column2....columnN FROM table_name
column2....columnN WHERE CONDITION-1 {AND|OR} CONDITION-2;
FROM table_name;
SELECT * FROM CUSTOMERS WHERE ID=123 OR
ID=124;

SELECT DISTINCT ID, Name,AGE FROM


CUSTOMERS

SELECT * FROM Customers WHERE NOT ADDRESS=DBU';


SELECT * FROM Customers
WHERE ADDRESS=DBU' AND (NAME=ABEBE' OR ADDRESS=DBU')
;
05/26/2025 Fundamentals of Database Systems 24
SQL Queries …
SQL IN Clause SQL BETWEEN Clause
SELECT column1, column2....columnN SELECT column1, column2....columnN
FROM table_name FROM table_name
WHERE column_name IN (val-1, val-2,...val-N); WHERE column_name BETWEEN val-1 AND val-2;

SELECT * FROM CUSTOMERS WHERE NAME IN ('Abebe','Melaku');

SELECT ID,NAME,AGE,ADDRESS,SALARY FROM


CUSTOMERS WHERE ID BETWEEN 125 AND 128;

The IN operator allows you to specify multiple values in a WHERE clause.


The IN operator is a shorthand for multiple OR conditions.

05/26/2025 Fundamentals of Database Systems 25


SQL Queries …
SQL LIKE Clause:
LIKE Operator Description
SELECT column1, column2....columnN
FROM table_name WHERE CustomerName LIKE 'a Finds any values that start with
%' "a"
WHERE column_name LIKE { PATTERN };
WHERE CustomerName LIKE Finds any values that end with
SELECT ID, NAME,AGE,ADDRESS,SALARY FROM '%a' "a"
CUSTOMERS WHERE AGE LIKE 30; WHERE CustomerName LIKE Finds any values that have "or"
'%or%' in any position

WHERE CustomerName LIKE '_r Finds any values that have "r" in
%' the second position

WHERE CustomerName LIKE Finds any values that start with


SELECT ID, NAME,AGE,ADDRESS,SALARY FROM 'a__%' "a" and are at least 3 characters
CUSTOMERS WHERE ID LIKE 123; in length
WHERE ContactName LIKE 'a%o' Finds any values that start with
"a" and ends with "o"

05/26/2025 Fundamentals of Database Systems 26


SQL Queries …
SQL ORDER BY Clause SQL GROUP BY Clause
SELECT column1, column2....columnN FROM table_name SELECT SUM(column_name) FROM table_name
WHERE CONDITION ORDER BY column_name {ASC| WHERE CONDITION GROUP BY column_name;
DESC}; SELECT NAME, SUM(SALARY) FROM
CUSTOMERS GROUP BY NAME;
SELECT ID,NAME,AGE,ADDRESS,SALARY FROM This would produce the following result
CUSTOMERS ORDER BY NAME ASC
This would produce the following result

05/26/2025 Fundamentals of Database Systems 27


SQL Queries …
SQL TOP Clause SELECT TOP 3 * FROM
 The SQL TOP clause is used CUSTOMERS;
to fetch a TOP N number or
X percent records from a ta This would produce the following result:

SELECT TOP number|percent column_name(s)


FROM table_name
WHERE [condition]

SQL> SELECT * FROM CUSTOMERS


LIMIT 3;
SELECT * FROM CUSTOMERS
WHERE ROWNUM <= 3;

05/26/2025 Fundamentals of Database Systems 28


SQL HAVING CLAUSE SELECT column1, column2 FROM table1, table2
 The HAVING clause enables you to WHERE [ conditions ]
specify conditions that filter which GROUP BY column1, column2
HAVING [ conditions ]
group results appear in the final ORDER BY column1, column2
results.
 The WHERE clause places conditions
on the selected columns, whereas the
HAVING clause places conditions on
groups created by the GROUP BY
clause.
 The HAVING clause must follow the
GROUP BY clause in a query and must
also precede the ORDER BY clause if
used. The following is the syntax of the
SELECT statement, including the
HAVING clause:
05/26/2025 Fundamentals of Database Systems 29
SQL Queries …
SQL COUNT() Function AVG() and SUM() Functions
SELECT COUNT(column_name) FROM table_name
WHERE CONDITION; SQL HAVING Clause: SELECT AVG(column_name) FROM table_name
WHERE condition;
SELECT COUNT(*) FROM CUSTOMERS WHERE
NAME='ABEBE';
This would produce the following result SELECT AVG(SALARY) FROM CUSTOMERS WHERE AGE>23;
This would produce the following result

SELECT COUNT(*) FROM CUSTOMERS SELECT SUM(column_name) FROM table_name


WHERE condition;

SELECT SUM(SALARY) FROM CUSTOMERS WHERE AGE>23;

05/26/2025 Fundamentals of Database Systems 30


SQL Queries …
SQL UPDATE Statement SQL DELETE Statement
DELETE FROM table_name WHERE {CONDITION};
UPDATE table_name SET column1 = value1, column2 = DELETE FROM table_name;(delete all )
value2....columnN=valueN [ WHERE CONDITION ];
DELETE FROM CUSTOMERS WHERE AGE=30;
UPDATE CUSTOMERS SET NAME = 'Abrham', ADDRESS= 'AA‘ WHERE ID = 12; The "Customers" table will now look like this:
Original
table
Before
update

The selection from the "Customers" table will now look like this:

After
After
Deleted
update
2 rows

05/26/2025 Fundamentals of Database Systems 31


SQL Queries …
SQL DROP TABLE Statement
DROP TABLE table_name;

SQL CREATE INDEX Statement:


CREATE UNIQUE INDEX index_name
ON table_name ( column1, column2,...columnN);

SQLALTER
DROP INDEX
TABLE Statement:
table_name
DROP INDEX index_name;

SQL DESC Statement:


DESC table_name;

TRUNCATE TABLE table_name;


SQL TRUNCATE TABLE Statement:
05/26/2025 Fundamentals of Database Systems 32
SQL Queries …
SQL ALTER TABLE Statement:
ALTER TABLE table_name {ADD|DROP|MODIFY} column_name
{data_ype};

SQLALTER TABLE Statement (Rename)


ALTER TABLE table_name RENAME TO new_table_name;

05/26/2025 Fundamentals of Database Systems 33


SQL Data Types
 SQL Server offers six categories of data types for your use
Exact Numeric Data Types

05/26/2025 Fundamentals of Database Systems 34


SQL Data Types
 SQL Server offers six categories of data types for your use
Approximate Numeric Data Types

05/26/2025 Fundamentals of Database Systems 35


SQL Data Types
 SQL Server offers six categories of data types for your use

05/26/2025 Fundamentals of Database Systems 36


SQL Data Types
 SQL Server offers six categories of data types for your use
Unicode Character Strings Data Types:

Binary Data Types

05/26/2025 Fundamentals of Database Systems 37


SQL Data Types

05/26/2025 Fundamentals of Database Systems 38


SQL Operators
 An operator is a reserved word or a character used primarily in
an SQL statement's WHERE clause to perform operation(s), such
as comparisons and arithmetic operations.
 Operators are used to specify conditions in an SQL statement and
to serve as conjunctions for multiple conditions in a statement.
 Arithmetic operators
 Comparison operators
 Logical operators
 Operators used to negate conditions

05/26/2025 Fundamentals of Database Systems 39


SQL Arithmetic Operators:

05/26/2025 Fundamentals of Database Systems 40


SQL Arithmetic Operators>Example

05/26/2025 Fundamentals of Database Systems 41


SQL Comparison Operators:
Assume variable a holds 10 and variable b holds 20, then:

05/26/2025 Fundamentals of Database Systems 42


SQL Logical Operators:
Here is a list of all the logical operators available in SQL.

05/26/2025 Fundamentals of Database Systems 43


FOREIGN Key:
 A foreign key is a key used to link two tables together. This is sometimes called a referencing key.
 Primary key field from one table and insert it into the other table where it becomes a foreign key i.e., 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 can not have two records having the same value of that field(s).
CREATE TABLE ORDERS (
OID INT NOT NULL,
DATE DATETIME,
CUSTOMER_ID INT references CUSTOMERS(ID),
AMOUNT int,
PRIMARY KEY (OID)
);
If ORDERS table has already been created, and the foreign key has not yet been, use the syntax for specifying a foreign key by altering a
table.
ALTER TABLE ORDERS ADD FOREIGN KEY (Customer_ID) REFERENCES CUSTOMERS (ID);
To drop a FOREIGN KEY constraint, use the following SQL:
ALTER TABLE ORDERS DROP FOREIGN KEY;

05/26/2025 Fundamentals of Database Systems 44


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.
 Consider the following two tables, (a) CUSTOMERS table is as
follows: and (b) Another table is ORDERS as follows:

a
b

05/26/2025 Fundamentals of Database Systems 45


SQL Joins…
Now, let us join these two tables in our SELECT statement as
follows:
SELECT ID, NAME, AGE, AMOUNT
FROM CUSTOMERS, ORDERS WHERE CUSTOMERS.ID = ORDERS.CUSTOMER_ID;

SELECT OID, NAME, AGE, AMOUNT FROM CUSTOMERS, ORDERS WHERE CUSTOMERS.ID = ORDERS.CUSTOMER_ID;

Example

05/26/2025 Fundamentals of Database Systems 46


SQL Join 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.
 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.

05/26/2025 Fundamentals of Database Systems 47


INNER JOIN
 The most frequently used and important of the joins is the INNER
JOIN. They are also referred to as an EQUIJOIN.
 The INNER JOIN creates a new result table by combining column
values of two tables (table1 and table2) based upon the join-
predicate. The query compares each row of table1 with each row
of table2 to find all pairs of rows which satisfy the join-predicate.
When the join-predicate is satisfied, column values for each
matched pair of rows of A and B are combined into a result row.

05/26/2025 Fundamentals of Database Systems 48


INNER JOIN
SELECT table1.column1, table2.column2...
FROM table1
INNER JOIN table2
ON table1.common_filed = table2.common_field;
Example:

SELECT ID, NAME, AMOUNT, DATE FROM CUSTOMERS INNER JOIN


ORDERS ON CUSTOMERS.ID = ORDERS.CUSTOMER_ID;
This would produce the following result:

05/26/2025 Fundamentals of Database Systems 49


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 if the ON
clause matches 0 (zero) records in right table, the join will still
return a row in the result, but with NULL in each column from
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 predicate.

05/26/2025 Fundamentals of Database Systems 50


LEFT JOIN…
SELECT table1.column1, table2.column2...
FROM table1 LEFT JOIN table2
ON table1.common_filed = table2.common_field;
SELECT ID, NAME, AMOUNT, DATE FROM CUSTOMERS LEFT JOIN ORDERS
ON CUSTOMERS.ID = ORDERS.CUSTOMER_ID;
This would produce the following result:

05/26/2025 Fundamentals of Database Systems 51


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 if the ON
clause matches 0 (zero) records in left table, the join will still
return a row in the result, but with NULL in each column from 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 predicate.

05/26/2025 Fundamentals of Database Systems 52


RIGHT JOIN…
SELECT table1.column1, table2.column2... FROM table1
RIGHT JOIN table2 ON table1.common_filed =
table2.common_field;
SELECT ID, NAME, AMOUNT, DATE FROM CUSTOMERS RIGHT JOIN ORDERS ON CUSTOMERS.ID =
ORDERS.CUSTOMER_ID;

This would produce the following result:

05/26/2025 Fundamentals of Database Systems 53


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.
SELECT table1.column1, table2.column2...
FROM table1 FULL JOIN table2 ON table1.common_filed = table2.common_field;

SELECT ID, NAME, AMOUNT, DATE FROM CUSTOMERS FULL JOIN ORDERS ON CUSTOMERS.ID = ORDERS.CUSTOMER_ID;
This would produce the following result:

05/26/2025 Fundamentals of Database Systems 54


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.

SELECT table1.column1, table2.column2...


FROM table1, table2 [, table3 ]

05/26/2025 Fundamentals of Database Systems 55


CARTESIAN JOIN…
SELECT ID, NAME, AMOUNT, DATE FROM CUSTOMERS, ORDERS;
This would produce the following result:

This table is continues

05/26/2025 Fundamentals of Database Systems 56


SQL Unions Clause
 The SQL UNION clause/operator is used to combine the results of
two or more SELECT statements without returning any duplicate
rows.
 To use UNION, each SELECT must have the same number of
columns selected, the same number of column expressions, the
same data type, and have them in the same order, but they do
not have to be the same
SELECT column1 [, column2 ]
FROM table1 [, table2 ]
[WHERE condition]
UNION SELECT column1 [, column2 ]
FROM table1 [, table2 ]
[WHERE condition]

05/26/2025 Fundamentals of Database Systems 57


SQL Unions Clause
SELECT ID, NAME, AMOUNT, DATE FROM
CUSTOMERS LEFT JOIN ORDERS ON CUSTOMERS.ID = ORDERS.CUSTOMER_ID
UNION SELECT ID, NAME, AMOUNT, DATE FROM CUSTOMERS RIGHT JOIN ORDERS
ON CUSTOMERS.ID = ORDERS.CUSTOMER_ID;

This would produce the following result:

05/26/2025 Fundamentals of Database Systems 58


The UNION ALL Clause:
 The UNION ALL operator is used to combine the results of two SELECT statements
including duplicate rows.
 The same rules that apply to UNION apply to the UNION ALL operator.

SELECT column1 [, column2 ]


FROM table1 [, table2 ]
[WHERE condition]
UNION ALL
SELECT column1 [, column2 ]
FROM table1 [, table2 ]
[WHERE condition]

05/26/2025 Fundamentals of Database Systems 59


The UNION ALL Clause…
SELECT ID, NAME, AMOUNT, DATE
FROM CUSTOMERS LEFT JOIN ORDERS ON CUSTOMERS.ID = ORDERS.CUSTOMER_ID
UNION ALL
SELECT ID, NAME, AMOUNT, DATE FROM CUSTOMERS RIGHT JOIN ORDERS ON CUSTOMERS.ID =
ORDERS.CUSTOMER_ID

This would produce the following result:

05/26/2025 Fundamentals of Database Systems 60


INTERSECT Clause
 The SQL INTERSECT clause/operator is used to combine two
SELECT statements, but returns rows only from the first SELECT
statement that are identical to a row in the second SELECT
statement. This means INTERSECT returns only common rows
returned by the two SELECT statements.
 Just as with the UNION operator, the same rules apply when
using the INTERSECT operator. MySQL does not support
INTERSECT operator
SELECT column1 [, column2 ]
FROM table1 [, table2 ] [WHERE condition]
INTERSECT
SELECT column1 [, column2 ] FROM table1 [, table2 ] [WHERE
condition]
05/26/2025 Fundamentals of Database Systems 61
INTERSECT Clause
SELECT ID, NAME, AMOUNT, DATE FROM CUSTOMERS LEFT JOIN ORDERS ON CUSTOMERS.ID = ORDERS.CUSTOMER_ID
INTERSECT SELECT ID, NAME, AMOUNT, DATE FROM CUSTOMERS RIGHT JOIN ORDERS ON CUSTOMERS.ID =
ORDERS.CUSTOMER_ID;

This would produce the following result:

05/26/2025 Fundamentals of Database Systems 62


SQL Alias Syntax
 You can rename a table or a column temporarily by giving
another name known as alias.
 The use of table aliases means to rename a table in a particular
SQL statement. The renaming is a temporary change and the
actual table name does not change in the database.
 The column aliases are used to rename a table's columns for the
purpose of a particular SQL query.
The basic syntax of table alias is as follows: The basic syntax of column alias is as follows

SELECT column1, column2.... SELECT column_name AS alias_name


FROM table_name AS alias_name FROM table_name
WHERE [condition]; WHERE [condition];

05/26/2025 Fundamentals of Database Systems 63


SQL Alias Syntax…
following is the usage of table alias:
Following is the usage of column alias:
SELECT C.ID, C.NAME, C.AGE, O.AMOUNT SELECT ID AS CUSTOMER_ID, NAME AS
FROM CUSTOMERS AS C, ORDERS AS O CUSTOMER_NAME
WHERE C.ID = O.CUSTOMER_ID; FROM CUSTOMERS WHERE SALARY IS NOT NULL;
This would produce the following result:

05/26/2025 Fundamentals of Database Systems 64


SQL Indexes
 Indexes are special lookup tables that the database search engine can use to speed
up data retrieval. Simply put, an index is a pointer to data in a table. An index in a
database is very similar to an index in the back of a book.
 For example, if you want to reference all pages in a book that discuss a certain topic,
you first refer to the index, which lists all topics alphabetically and are then referred
to one or more specific page numbers.
 An index helps speed up SELECT queries and WHERE clauses, but it slows down data
input, with UPDATE and INSERT statements. Indexes can be created or dropped with
no effect on the data.
 Creating an index involves the CREATE INDEX statement, which allows you to name
the index, to specify the table and which column or columns to index, and to
indicate whether the index is in ascending or descending order.
 Indexes can also be unique, similar to the UNIQUE constraint, in that the index
prevents duplicate entries in the column or combination of columns on which
there's an index.
05/26/2025 Fundamentals of Database Systems 65
SQL Indexes
The CREATE INDEX Command:
CREATE INDEX index_name
ON table_name ( column1, column2.....);

CREATE INDEX idx_age


ON CUSTOMERS ( AGE );

DROP an INDEX Constraint:


To drop an INDEX constraint, use the following SQL:
ALTER TABLE CUSTOMERS
DROP INDEX idx_age;

05/26/2025 Fundamentals of Database Systems 66


SQL TRUNCATE TABLE
 The SQL TRUNCATE TABLE command is used to delete complete data from an existing
table.
 You can also use DROP TABLE command to delete complete table but it would remove
complete table structure form the database and you would need to re-create this table
once again if you wish you store some data.
TRUNCATE TABLE table_name;

 Consider the CUSTOMERS table having the following records:


TRUNCATE TABLE CUSTOMERS;

 Now, CUSTOMERS table is truncated and following would be the output from SELECT
statement:
SELECT * FROM CUSTOMERS;
Empty set (0.00 sec)
05/26/2025 Fundamentals of Database Systems 67
For More Information
 tutorialspoint.com

05/26/2025 Fundamentals of Database Systems 68


05/26/2025 Introduction to Java and OO Concepts 69

You might also like