0% found this document useful (0 votes)
5 views16 pages

Labmanual

SQL, or Structured Query Language, is a standard language for accessing and manipulating databases, established by ANSI in 1986 and ISO in 1987. It allows users to execute queries, retrieve, insert, update, and delete records, as well as create databases and tables. The document covers various SQL statements, including CREATE, ALTER, DELETE, and SELECT, along with constraints, data types, and functions for managing and querying data.

Uploaded by

jad man
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views16 pages

Labmanual

SQL, or Structured Query Language, is a standard language for accessing and manipulating databases, established by ANSI in 1986 and ISO in 1987. It allows users to execute queries, retrieve, insert, update, and delete records, as well as create databases and tables. The document covers various SQL statements, including CREATE, ALTER, DELETE, and SELECT, along with constraints, data types, and functions for managing and querying data.

Uploaded by

jad man
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 16

SQL Basics

What is SQL?

 SQL stands for Structured Query Language


 SQL lets you access and manipulate databases
 SQL became a standard of the American National Standards Institute (ANSI) in 1986, and of
the International Organization for Standardization (ISO) in 1987

What Can SQL do?

 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

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.

SQL Statements

Most of the actions you need to perform on a database are done with SQL statements.

SQL Comments

Comments are used to explain sections of SQL statements, or to prevent execution of SQL
statements.

1. Single Line Comments

Single line comments start with --.

Any text between -- and the end of the line will be ignored (will not be executed).

Example:
--Select all:
SELECT * FROM Customers;

2. Multi-line Comments

Multi-line comments start with /* and end with */. Any text between /* and */ will be ignored.
Example:
/*Select all the columns
of all the records
in the Customers table:*/
SELECT * FROM Customers;

The SQL CREATE DATABASE Statement

The CREATE DATABASE statement is used to create a new SQL database.

Syntax: CREATE DATABASE databasename;

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

CREATE DATABASE testDB;

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,
....
);

SQL CREATE TABLE Example

The following example creates a table called "Persons" that contains five columns: PersonID,
LastName, FirstName, Address, and City:

CREATE TABLE Persons (


PersonID int,
LastName varchar(255),
FirstName varchar(255),
Address varchar(255),
City varchar(255)
);

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 SQL DROP DATABASE Statement

The DROP DATABASE statement is used to drop an existing SQL database.

Syntax: DROP DATABASE databasename;


The SQL DROP TABLE Statement

The DROP TABLE statement is used to drop an existing table in a database.

Syntax: DROP TABLE table_name;


SQL ALTER TABLE Statement

The ALTER TABLE statement is used to add, delete, or modify columns in an existing table.

The ALTER TABLE statement is also used to add and drop various constraints on an existing table.

ALTER TABLE - ADD Column

To add a column in a table, use the following syntax:

ALTER TABLE table_name


ADD column_name datatype;

The following SQL adds an "Email" column to the "Customers" table:

ALTER TABLE Customers


ADD Email varchar(255);

To add primary and foreign key columns

ALTER TABLE student ADD id int not null primary key(id); // to add PK
ALTER TABLE instructor ADD id int foreign key references departmen(Dnum)// to add FK

ALTER TABLE - DROP COLUMN

To delete a column in a table, use the following syntax (notice that some database systems don't
allow deleting a column):

ALTER TABLE table_name


DROP COLUMN column_name;

The following SQL deletes the "Email" column from the "Customers" table:

ALTER TABLE Customers


DROP COLUMN Email;

To drop primary and foreign key columns

ALTER TABLE student DROP constraint “PK_Name” // to delete PK


ALTER TABLE test DROP constraint “FK_Name” // to delete FK

ALTER TABLE – ALTER COLUMN

To change the data type of a column in a table, use the following syntax:

SQL Server:
ALTER TABLE table_name
ALTER COLUMN column_name datatype;

Now we want to add a column named "DateOfBirth" in the "Persons" table.

ALTER TABLE Persons ADD DateOfBirth date;

Now we want to change the data type of the column named "DateOfBirth" in the "Persons" table.

ALTER TABLE Persons ALTER COLUMN DateOfBirth year;

Next, we want to delete the column named "DateOfBirth" in the "Persons" table.

ALTER TABLE Persons DROP COLUMN DateOfBirth;


SQL Constraints

SQL constraints are used to specify rules for data in a table.

SQL Create Constraints

Constraints can be specified when the table is created with the CREATE TABLE statement, or after
the table is created with the ALTER TABLE statement.

Syntax:
CREATE TABLE table_name (
column1 datatype constraint,
column2 datatype constraint,
column3 datatype constraint,
....
);

The following constraints are commonly used in SQL:

 NOT NULL - Ensures that a column cannot have a NULL value


 UNIQUE - Ensures that all values in a column are different
 PRIMARY KEY - A combination of a NOT NULL and UNIQUE. Uniquely identifies each
row in a table
 FOREIGN KEY - Uniquely identifies a row/record in another table
 CHECK - Ensures that all values in a column satisfies a specific condition
 DEFAULT - Sets a default value for a column when no value is specified
 INDEX - Used to create and retrieve data from the database very quickly

SQL NOT NULL Constraint

By default, a column can hold NULL values. The NOT NULL constraint enforces a column to NOT
accept NULL values. This enforces a field to always contain a value, which means that you cannot
insert a new record, or update a record without adding a value to this field.

SQL NOT NULL on CREATE TABLE


The following SQL ensures that the "ID", "LastName", and "FirstName" columns will NOT accept
NULL values when the "Persons" table is created:

CREATE TABLE Persons (


ID int NOT NULL,
LastName varchar(255) NOT NULL,
FirstName varchar(255) NOT NULL,
Age int
);

SQL UNIQUE Constraint

The UNIQUE constraint ensures that all values in a column are different. Both the UNIQUE and
PRIMARY KEY constraints provide a guarantee for uniqueness for a column or set of columns. A
PRIMARY KEY constraint automatically has a UNIQUE constraint. However, you can have many
UNIQUE constraints per table, but only one PRIMARY KEY constraint per table.

SQL UNIQUE Constraint on CREATE TABLE

The following SQL creates a UNIQUE constraint on the "ID" column when the "Persons" table is
created:

CREATE TABLE Persons (


ID int NOT NULL UNIQUE,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Age int
);

SQL PRIMARY KEY Constraint

The PRIMARY KEY constraint uniquely identifies each record in a table. Primary keys must contain
UNIQUE values, and cannot contain NULL values. A table can have only one primary key, which
may consist of single or multiple fields.

CREATE TABLE Persons (


ID int NOT NULL PRIMARY KEY,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Age int
);

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 more complicated.

SQL Date Data Types


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:MI:SS
 SMALLDATETIME - format: YYYY-MM-DD HH:MI:SS
 TIMESTAMP - format: a unique number

Note: The date types are chosen for a column when you create a new table in your database!

SELECT * FROM Orders WHERE OrderDate='2008-11-11'

The SQL SELECT Statement

The SELECT statement is used to select data from a database. The data returned is stored in a result
table, called the result-set.

SELECT Syntax
SELECT column1, column2, ...
FROM table_name;

SELECT Column Example

The following SQL statement selects the "CustomerName" and "City" columns from the
"Customers" table:

SELECT CustomerName, City FROM Customers;

The following SQL statement selects all the columns from the "Customers" table:

SELECT * FROM Customers;

The SQL SELECT DISTINCT Statement

The SELECT DISTINCT statement is used to return only distinct (different) values. Inside a table, a
column often contains many duplicate values; and sometimes you only want to list the different
(distinct) values.

SELECT DISTINCT column1, column2, ...


FROM table_name;

The following SQL statement selects only the DISTINCT values from the "Country" column in the
"Customers" table:

SELECT DISTINCT Country FROM Customers;

The SQL WHERE Clause

The WHERE clause is used to filter records. The WHERE clause is used to extract only those
records that fulfill a specified condition.
SELECT column1, column2, ...
FROM table_name
WHERE condition;

The WHERE clause is not only used in SELECT statement, it is also used in UPDATE, DELETE
statement, etc.!

The following SQL statement selects all the customers from the country "Mexico", in the
"Customers" table:

SELECT * FROM Customers


WHERE Country='Mexico';

Text Fields vs. Numeric Fields

SQL requires single quotes around text values (most database systems will also allow double quotes).
However, numeric fields should not be enclosed in quotes:

SELECT * FROM Customers


WHERE CustomerID=1;

Operators in The WHERE Clause

The following operators can be used in the WHERE clause:

= [equal], <> (!=) [not equal], > [greater than],< [Less than], >= [greater than or equal], <= []less
than or equal, BETWEEN [Between a certain range],IN [To specify multiple possible values for a
column], LIKE [Search for a pattern]

The SQL AND, OR and NOT Operators

The WHERE clause can be combined with AND, OR, and NOT operators. The AND and OR
operators are used to filter records based on more than one condition:

 The AND operator displays a record if all the conditions separated by AND are TRUE.
 The OR operator displays a record if any of the conditions separated by OR is TRUE.
 The NOT operator displays a record if the condition(s) is NOT TRUE.

AND Syntax:
SELECT column1, column2, ...
FROM table_name
WHERE condition1 AND condition2 AND condition3 ...;

OR Syntax:
SELECT column1, column2, ...
FROM table_name
WHERE condition1 OR condition2 OR condition3 ...;
NOT Syntax:
SELECT column1, column2, ...
FROM table_name
WHERE NOT condition;

The following SQL statement selects all fields from "Customers" where country is "Germany" AND
city is "Berlin":

SELECT * FROM Customers


WHERE Country='Germany' AND City='Berlin';

The following SQL statement selects all fields from "Customers" where city is "Berlin" OR
"München":

SELECT * FROM Customers


WHERE City='Berlin' OR City='München';

The following SQL statement selects all fields from "Customers" where country is NOT "Germany":

SELECT * FROM Customers


WHERE NOT Country='Germany';

The SQL ORDER BY Keyword

The ORDER BY keyword is used to sort the result-set in ascending or descending order. The
ORDER BY keyword sorts the records in ascending order by default. To sort the records in
descending order, use the DESC keyword.

ORDER BY Syntax:
SELECT column1, column2, ...
FROM table_name
ORDER BY column1, column2, ... ASC|DESC;

The following SQL statement selects all customers from the "Customers" table, sorted
DESCENDING by the "Country" column:

SELECT * FROM Customers


ORDER BY Country DESC;

The following SQL statement selects all customers from the "Customers" table, sorted ascending by
the "Country" and descending by the "CustomerName" column:

SELECT * FROM Customers


ORDER BY Country ASC, CustomerName DESC;

How to 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.

IS NULL Syntax
SELECT column_names
FROM table_name
WHERE column_name IS NULL;

IS NOT NULL Syntax


SELECT column_names
FROM table_name
WHERE column_name IS NOT NULL;

The following SQL lists all customers with a NULL value in the "Address" field:

SELECT CustomerName, ContactName, Address


FROM Customers
WHERE Address IS NULL;

The SQL INSERT INTO Statement

The INSERT INTO statement is used to insert new records in a table. It is possible to write the
INSERT INTO statement in two ways. The first way specifies both the column names and the values
to be inserted:

INSERT INTO table_name (column1, column2, column3, ...)


VALUES (value1, value2, value3, ...);

If you are adding values for all the columns of the table, you do not need to specify the column
names in the SQL query. However, make sure the order of the values is in the same order as the
columns in the table. The INSERT INTO syntax would be as follows:

INSERT INTO table_name


VALUES (value1, value2, value3, ...);

The following SQL statement inserts a new record in the "Customers" table:

INSERT INTO Customers (CustomerName, ContactName, Address, City, PostalCode, Country)


VALUES ('Cardinal', 'Tom B. Erichsen', 'Skagen 21', 'Stavanger', '4006', 'Norway');

Insert Data Only in Specified Columns

It is also possible to only insert data in specific columns. The following SQL statement will insert a
new record, but only insert data in the "CustomerName", "City", and "Country" columns
(CustomerID will be updated automatically):

INSERT INTO Customers (CustomerName, City, Country)


VALUES ('Cardinal', 'Stavanger', 'Norway');

The SQL UPDATE Statement

The UPDATE statement is used to modify the existing records in a table.


UPDATE Syntax
UPDATE table_name
SET column1 = value1, column2 = value2, ...
WHERE condition;

UPDATE Table

The following SQL statement updates the first customer (CustomerID = 1) with a new contact
person and a new city.

UPDATE Customers
SET ContactName = 'Alfred Schmidt', City= 'Frankfurt'
WHERE CustomerID = 1;

UPDATE Multiple Records

It is the WHERE clause that determines how many records that will be updated.

The following SQL statement will update the contactname to "Juan" for all records where country is
"Mexico":

UPDATE Customers
SET ContactName='Juan'
WHERE Country='Mexico';

The SQL DELETE Statement

The DELETE statement is used to delete existing records in a table.

DELETE FROM table_name WHERE condition;

The following SQL statement deletes the customer "Alfreds Futterkiste" from the "Customers" table:

DELETE FROM Customers WHERE CustomerName='Alfreds Futterkiste';

Delete All Records

It is possible to delete all rows in a table without deleting the table. This means that the table
structure, attributes, and indexes will be intact:

DELETE FROM table_name;

The following SQL statement deletes all rows in the "Customers" table, without deleting the table:

DELETE FROM Customers;

The SQL MIN() and MAX() Functions

The MIN() function returns the smallest value of the selected column. The MAX() function returns
the largest value of the selected column.

MIN() Syntax
SELECT MIN(column_name)
FROM table_name
WHERE condition;

MAX() Syntax
SELECT MAX(column_name)
FROM table_name
WHERE condition;

The following SQL statement finds the price of the cheapest product:

SELECT MIN(Price) AS SmallestPrice


FROM Products;

The following SQL statement finds the price of the most expensive product:

SELECT MAX(Price) AS LargestPrice


FROM Products;

The SQL COUNT(), AVG() and SUM() Functions

The COUNT() function returns the number of rows that matches a specified criteria. The AVG()
function returns the average value of a numeric column. The SUM() function returns the total sum of
a numeric column.

COUNT() Syntax
SELECT COUNT(column_name)
FROM table_name
WHERE condition;

AVG() Syntax
SELECT AVG(column_name)
FROM table_name
WHERE condition;

SUM() Syntax
SELECT SUM(column_name)
FROM table_name
WHERE condition;

The following SQL statement finds the number of products:

SELECT COUNT(ProductID)
FROM Products;

The following SQL statement finds the average price of all products:

SELECT AVG(Price)
FROM Products;
The following SQL statement finds the sum of the "Quantity" fields in the "OrderDetails" table:

SELECT SUM(Quantity)
FROM OrderDetails;

SQL Wildcard Characters

A wildcard character is used to substitute any other character(s) in a string.

Wildcard characters are used with the SQL LIKE operator. The LIKE operator is used in a WHERE
clause to search for a specified pattern in a column.

There are two wildcards used in conjunction with the LIKE operator:

 % - The percent sign represents zero, one, or multiple characters


 _ - The underscore represents a single character

The SQL LIKE Operator

The LIKE operator is used in a WHERE clause to search for a specified pattern in a column.

There are two wildcards used in conjunction with the LIKE operator:

 % - The percent sign represents zero, one, or multiple characters


 _ - The underscore represents a single character

LIKE Syntax
SELECT column1, column2, ...
FROM table_name
WHERE columnN LIKE pattern;

The following SQL statement selects all customers with a CustomerName starting with "a":

SELECT * FROM Customers


WHERE CustomerName LIKE 'a%';

The following SQL statement selects all customers with a CustomerName ending with "a":

SELECT * FROM Customers


WHERE CustomerName LIKE '%a';

The following SQL statement selects all customers with a CustomerName that have "r" in the second
position:

SELECT * FROM Customers


WHERE CustomerName LIKE '_r%';

SQL Aliases

SQL aliases are used to give a table, or a column in a table, a temporary name. Aliases are often used
to make column names more readable. An alias only exists for the duration of the query.
Alias Column Syntax
SELECT column_name AS alias_name
FROM table_name;

Alias Table Syntax


SELECT column_name(s)
FROM table_name AS alias_name;

The following SQL statement creates two aliases, one for the CustomerID column and one for the
CustomerName column:

SELECT CustomerID AS ID, CustomerName AS Customer


FROM Customers;

The following SQL statement creates two aliases, one for the CustomerName column and one for the
ContactName column. Note: It requires double quotation marks or square brackets if the alias name
contains spaces:

SELECT CustomerName AS Customer, ContactName AS [Contact Person]


FROM Customers;

SQL JOIN

A JOIN clause is used to combine rows from two or more tables, based on a related column between
them.

Different Types of SQL JOINs

Here are the different types of the JOINs in SQL:

 (INNER) JOIN: Returns records that have matching values in both tables
 LEFT (OUTER) JOIN: Return all records from the left table, and the matched records from
the right table
 RIGHT (OUTER) JOIN: Return all records from the right table, and the matched records
from the left table
 FULL (OUTER) JOIN: Return all records when there is a match in either left or right table

SQL INNER JOIN Keyword

The INNER JOIN keyword selects records that have matching values in both tables.

INNER JOIN Syntax


SELECT column_name(s)
FROM table1
INNER JOIN table2 ON table1.column_name = table2.column_name;
The following SQL statement selects all orders with customer information:

SELECT Orders.OrderID, Customers.CustomerName


FROM Orders
INNER JOIN Customers ON Orders.CustomerID = Customers.CustomerID;

SQL LEFT JOIN Keyword

The LEFT JOIN keyword returns all records from the left table (table1), and the matched records
from the right table (table2). The result is NULL from the right side, if there is no match.

LEFT JOIN Syntax


SELECT column_name(s)
FROM table1
LEFT JOIN table2 ON table1.column_name = table2.column_name;

The following SQL statement will select all customers, and any orders they might have:

SELECT Customers.CustomerName, Orders.OrderID


FROM Customers
LEFT JOIN Orders ON Customers.CustomerID = Orders.CustomerID
ORDER BY Customers.CustomerName;

SQL RIGHT JOIN Keyword

The RIGHT JOIN keyword returns all records from the right table (table2), and the matched records
from the left table (table1). The result is NULL from the left side, when there is no match.

RIGHT JOIN Syntax


SELECT column_name(s)
FROM table1
RIGHT JOIN table2 ON table1.column_name = table2.column_name;

The following SQL statement will return all employees, and any orders they might have placed:

SELECT Orders.OrderID, Employees.LastName, Employees.FirstName


FROM Orders
RIGHT JOIN Employees ON Orders.EmployeeID = Employees.EmployeeID
ORDER BY Orders.OrderID;

SQL FULL OUTER JOIN Keyword

The FULL OUTER JOIN keyword return all records when there is a match in either left (table1) or
right (table2) table records.

Note: FULL OUTER JOIN can potentially return very large result-sets!

FULL OUTER JOIN Syntax


SELECT column_name(s)
FROM table1
FULL OUTER JOIN table2 ON table1.column_name = table2.column_name;

The following SQL statement selects all customers, and all orders:

SELECT Customers.CustomerName, Orders.OrderID


FROM Customers
FULL OUTER JOIN Orders ON Customers.CustomerID=Orders.CustomerID
ORDER BY Customers.CustomerName;

Exercise with solutions

Let us consider table named Employee and with using this table write different SQL Queries
Query 1 : List the employee whose employee number is 100.
Answer:
Simple where clause is used to write this query,
Select * from Employee where employee_Num=100;

Query 2 : List the Employee whose salary is between 5K to 10.


Answer:
Here user needs to use between..and operator or where clause less than and greater than operator,
Solution 1 : Using Between..and operator
Select * from Employee where salary between 5000 and 10000;

Solution 2 : Using operators (Greater than and less than)


Select * from Employee where salary >= 5000 and salary <= 10000;

Query 3 : List the Employees whose name starts with ‘Ami’.


Answer :
We need to use like operator to achieve this,
Select * from Employees where name like ‘Ami%’;

Query 4 : List the Employees whose name starts with A and surname starts with S.
Answer :
We need to use like operator to achieve this,
Select * from Employees where name like ‘A%’ and surname like ‘S%’;

Query 5 : List the Employees who’s surname contains kar word.


Answer :
We need to use like operator to achieve this,
Select * from Employees where surname like ‘%kar%’;

Query 12 : Find Query to get information of Employee where Employee is not assigned to
the department
Answer:

We can achieve this using not in operator,


Select * from Employees where Dept_no Not in(Select Department_no from Employee);

You might also like