SQL Notes Part 1
SQL Notes Part 1
𝐃𝐚𝐭𝐚
• Data is a collection of facts, such as numbers, words, measurements,
observations or descriptions of things.
Examples-
o Numbers (e.g., 42,3.14)
o Words (e.g., “Hello”, “SQL”)
o Measurements (e.g., height , weight)
o Observations (e.g., “It is raining”)
Database
• A database is an organized collection of data, generally stored and
accessed electronically from a computer system.
• It allow for efficient storage, retrieval, and management of data.
Examples of Databases:
o E-commerce platforms (e.g., Amazon)
o Social media platforms (e.g., Facebook)
Database Management System (DBMS)
• Database management system is a software which is used to manage the
database.
• DBMS provides an interface to perform various operations like-
1. Creating databases, tables, and objects.
2. Inserting, updating, and deleting data.
3. Dropping databases, tables, and objects.
4. Provides data security.
• Some popular DBMS softwares are MS SQL
SERVER,Oracle,MySQL,IBM,DB2,PostgreSQL etc.
Table
• A table in a database is a collection of rows and columns.
• It is used to organize and store data in a structured format.
Row and Column
• A row is a horizontal arrangement of data moving from right to left. It is
often referred to as a record or a tuple. It represents individual data
entries.
• A column is a vertical arrangement of data moving from top to bottom. It
is often referred to as an attribute or a field. It represents the
characteristics or properties of the data.
Example- A "Customers" table might have columns like CustomerID, Name,
Email, and Phone with each row representing a different customer.
SQL
• SQL stands for Structured Query Language was initially developed by
IBM.
• Initially it was called as SEQUEL (Structure English Query Language)
• SQL is a programming language used to interact with database.
• SQL allows you to create, read, update, and delete (CRUD) data in a
relational database.
SQL Data Types
• Data Types define the type of data that can be stored in a table column.
• It ensures data integrity and optimizes storage.
1. CHAR-
• Can store characters of fixed length.
• The size parameter specifies the column length in characters can
be from 0 to 255.
2. VARCHAR-
• Can store characters up to given length.
• The size parameter specifies the maximum column length in
characters can be from 0 to 65535.
1. INT-
• Used for storing whole numbers without decimal.
2. FLOAT-
• Used for storing numbers without decimal.
• Float gives approximate value while performing calculations.
D. BIT Datatype- BIT data type can store either True or False values
(represents by 1 and 0).
Example-
CREATE TABLE Employees (
EmployeeID INT,
FirstName VARCHAR(50),
LastName CHAR(20),
Salary DECIMAL(10, 2),
BirthDate DATE,
HireTime TIME,
IsActive BIT
);
SQL Commands
1. Create a Database-
Syntax-
Example-
Syntax-
USE database_name;
Example-
USE SalesDB;
2. Create Table-
Syntax-
Example-
1. Drop a Database-
Syntax-
Example-
2. Drop a Table-
Syntax-
Example-
DROP TABLE CUSTOMERS;
Insert Command
Syntax-
Example-
INSERT INTO CUSTOMERS (ID, NAME, AGE, ADDRESS, SALARY)
VALUES (1, 'Ramesh', 32, 'Ahmedabad', 2000.00);
INSERT INTO CUSTOMERS (ID, NAME, AGE, ADDRESS, SALARY)
VALUES (2, 'Khilan', 25, 'Delhi', 1500.00);
You can create a record in the CUSTOMERS table by using the second syntax as
shown below.
NOTE- 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.
Syntax-
Example-
Syntax-
INSERT INTO table_name (column1, column2, column3, ...)
VALUES (value1, value2, value3, ...);
Example-
To select all columns from a table, you can use the asterisk (*):
Syntax-
Example-
Syntax-
Example-
To fetch the ID, Name and Salary fields of the customers available in CUSTOMERS
table.
Syntax-
Example-
To fetch the ID, Name and Salary fields from the CUSTOMERS table for a
customer with the name Hardik.
Note- It is important to note that all the strings should be given inside single
quotes (''). Whereas, numeric values should be given without any quote
SELECT ID, NAME, SALARY
FROM CUSTOMERS
WHERE NAME = 'Hardik';
Example-
To fetch the ID, Name and Salary fields from the CUSTOMERS table, where the
salary is greater than 2000.
SELECT *
FROM CUSTOMERS
WHERE SALARY > 2000;
SQL Operators
• SQL operators are used to perform operations on data within queries.
• SQL operators are symbols or keywords that perform actions like
comparing values, doing math or combining conditions in queries to filter,
manipulate and analyze data in databases.
1. Arithmetic Operators-
• Used to perform mathematical operations on numeric values.
Common operators-
SELECT 10 + 5;
SELECT 10 - 5;
SELECT 10 * 5;
SELECT 10 / 5;
SELECT 10 % 5;
Common operators-
a) Equal (=): Checks if two values are equal, if yes then condition
becomes true.
Example-
SELECT * FROM CUSTOMERS WHERE ID = 3;
b) Not equal to (!= or <>): Checks if two values are not equal, if yes then
condition becomes true.
Example-
SELECT * FROM CUSTOMERS WHERE SALARY != 2000;
e) Greater than or Equal To (>=): Checks if one value is greater than or equal
to another.
Example-
SELECT * FROM CUSTOMERS WHERE SALARY >= 2000;
f) Less than or Equal To (<=): Checks if one value is less than or equal to
another.
Example-
SELECT * FROM CUSTOMERS WHERE SALARY <= 2000;
3. Logical Operators-
• Used to combine multiple conditions.
Common Operators-
Example-
To fetch the ID, Name and Salary fields from the CUSTOMERS table, where the
salary is greater than 2000 and the age is less than 25 years.
Example-
To fetch the ID, Name and Salary fields from the CUSTOMERS table, where the
salary is greater than 2000 OR the age is less than 25 years.
SELECT ID, NAME, SALARY
FROM CUSTOMERS
WHERE SALARY > 2000 OR age < 25;
Example-
To fetch the ID, Name and Salary fields from the CUSTOMERS table, whose salary
is not 2000.
Syntax-
SELECT column_name(s)
FROM table_name
WHERE column_name IN (value1, value2, ...);
Example-
Retrieve the ID, name, and address of customers living in either Mumbai, Delhi,
or Bhopal.
Syntax-
SELECT column1, column2, ...
FROM table_name
WHERE column_name BETWEEN low_value AND high_value;
Example-
Retrieve ID, NAME, AGE FROM CUSTOMERS WHERE AGE BETWEEN 24 AND 27
from the CUSTOMERS table.
SELECT *
FROM CUSTOMERS
WHERE SALARY BETWEEN 2000 AND 10000;
NULL
NULL
• NULL values represent missing value or unknown data.
values
• NULL is neither a space or zero(0).
repres
• NULL can’t be compared with any value/anything, not even to another
entNULL.
missin
g or
Example-
unkno
If you
wnhave a CUSTOMERS table and you want to insert a record for Bharti
without providing her age and address:
data
INSERT INTO CUSTOMERS (ID, NAME, SALARY)
VALUES (7, 'Bharti', 12000.00 );
In this case, if the AGE AND ADDRESS column is set to default to NULL, BHARTI
AGE AND ADDRESS value will be NULL.
Example-
If you do not want to provide a value for a column, you can assign NULL to that
column.
In this statement, we are inserting a new record into the CUSTOMERS table.
The ID is set to 8, the NAME is set to 'Rahul', AGE is set to 25, ADDRESS is set to
'Delhi' and the SALARY is set to NULL.
Syntax-
SELECT * FROM table_name WHERE column_name IS NULL;
Example-
Suppose you have a CUSTOMERS table, and you want to find all customers
whose salary is not provided (i.e., NULL):
SELECT * FROM CUSTOMERS WHERE SALARY IS NULL;
IS NOT NULL
This condition is used to check whether a column does not contain a NULL
value.
Syntax:
SELECT * FROM table_name WHERE column_name IS NOT NULL;
Example-
Using the same CUSTOMERS table, if you want to find all customers who have a
salary specified (i.e., not NULL):
SELECT * FROM CUSTOMERS WHERE SALARY IS NOT NULL;
DISTINCT
Syntax-
SELECT DISTINCT column1, column2, ...
FROM table_name;
Example-
Suppose you have a table called Customers with the following data:
If you want to retrieve distinct address from this table, you can use the
DISTINCT keyword like this:
SELECT DISTINCT ADDRESS
FROM CUSTOMERS;
If you want to select all unique rows from a table, you can use:
Syntax-
SELECT DISTINCT *
FROM table_name;
Note- This will return all columns from the table but only show distinct rows.
However, keep in mind that using DISTINCT * may not be efficient if your table
has many columns. It's usually better to specify only the columns you need.
Alias
Syntax-
The basic syntax of a table alias is as follows-
SELECT column_name AS alias_name
FROM table_name
WHERE [condition];
Result-
Here,
• Customer_Name is the alias for the NAME column from the CUSTOMERS
table.
• Order_Amount is the alias for the AMOUNT column from the ORDERS
table.
• Order_Date is the alias for the DATE column from the ORDERS table.
Result-
In SQL Server, the AS keyword is commonly used to create aliases, it is not
mandatory. You can create aliases without using AS by simply specifying the
alias name immediately after the column or table name.
1. Column Alias: Just place the alias name after the column name.
Syntax-
SELECT column_name alias_name;
2. Table Alias: Just place the alias name after the table name.
Syntax-
SELECT column_name FROM table_name alias_name;
Example- Here’s a full query using both types of aliases without the AS
keyword.
In SQL Server, both SELECT INTO and INSERT INTO SELECT can be used to copy
data from one table to another, but they are used differently.
1. SELECT INTO-
• SELECT INTO is used to create a new table and copy data into it at the
same time.
• It duplicates both the structure and data from an existing table into a
new one.
Example-
SELECT * INTO BACKUP_CUSTOMERS
FROM CUSTOMERS
WHERE ADDRESS = 'Delhi';
This will create a new table backup_customers and copy all rows from the
customers table where address= 'Delhi'.
B) Copy only Selected or Few Columns into a New Table-
Syntax-
SELECT columns
INTO new_table
FROM existing_table
WHERE condition(Optional);
Example-
SELECT NAME, ADDRESS INTO BACKUP_CUSTOMERSDETAIL
FROM CUSTOMERS;
Syntax-
INSERT INTO target_table (column1, column2, ...)
SELECT column1, column2, ...
FROM source_table
WHERE condition;
Example-
INSERT INTO SELECT statement to copy data from CUSTOMERS to
BACKUP_CUSTOMERS for customers who are older than 30.
Here,
• INSERT INTO BACKUP_CUSTOMERS: This specifies that you are
inserting data into the BACKUP_CUSTOMERS table.
• (ID, NAME, AGE, ADDRESS, SALARY): These are the columns in the
BACKUP_CUSTOMERS table that will receive the data.
• SELECT ID, NAME, AGE, ADDRESS, SALARY FROM CUSTOMERS: This
selects the corresponding columns from the CUSTOMERS table.
• WHERE AGE > 30: This condition ensures that only rows where the
AGE is greater than 30 are copied from CUSTOMERS to
BACKUP_CUSTOMERS.
B) Copy All Columns from one Table to Another Table-
Syntax-
INSERT INTO target_table
SELECT *
FROM source_table
WHERE condition;
Example-
INSERT INTO BACKUP_CUSTOMERS
SELECT *
FROM CUSTOMERS
WHERE ADDRESS ='Delhi';
Example- If you want to delete record from the customers table where
id =1.
DELETE FROM CUSTOMERS WHERE ID = 1;
2. Deleting All Rows:
Syntax-
DELETE FROM table_name;
Example-
If you want to delete all rows from a table without dropping the table
structure.
DELETE FROM CUSTOMERS;
Truncate Command
The TRUNCATE command removes all rows from a table and retains the
table structure for future use. Unlike DELETE, you cannot specify
conditions—it clears the entire table in one go.
It cannot be rolled back in some databases.
Faster than DELETE because it doesn't log individual row deletions.
Syntax-
TRUNCATE TABLE table_name;
Example-
TRUNCATE TABLE CUSTOMERS;
Update Command
Syntax-
UPDATE table_name
SET column1 = value1, column2 = value2, ...
WHERE condition;
Example-
If we want to update the ADDRESS for a customer whose ID number is 6
in the Customers table, the query would be:
UPDATE CUSTOMERS
SET ADDRESS = 'Pune'
WHERE ID = 6;
Example-
If you want to modify all the ADDRESS and the SALARY column values in
the CUSTOMERS table, you do not need to use the WHERE clause as the
UPDATE query would be –
UPDATE CUSTOMERS
SET ADDRESS = 'Pune', SALARY = 1000.00;
Alter Command
Syntax-
ALTER TABLE table_name
ADD column_name datatype;
Example-
ALTER TABLE ORDERS
ADD Address VARCHAR(255);
Syntax-
ALTER TABLE table_name
ALTER COLUMN column_name new_datatype;
Example-
ALTER TABLE ORDERS
ALTER COLUMN AMOUNT DECIMAL(12, 1);
3. Deleting Columns: You can remove unwanted columns from a
table using ALTER.
Syntax-
ALTER TABLE table_name
DROP COLUMN column_name;
Example-
ALTER TABLE ORDERS
DROP COLUMN ADDRESS;
RENAME
2. Renaming a Column-
Syntax-
sp_rename 'table_name.old_column_name', 'new_column_name';
Example-
sp_rename 'ORDERS.DATE_TIME', 'DATE';
Order By Clause
The ORDER BY clause in SQL is used to sort the result set/data in either
ascending or descending order, based on one or more columns.
Syntax-
SELECT column1, column2, ...
FROM table_name
ORDER BY column1 [ASC|DESC], column2 [ASC|DESC], ...;
Explanation:
column1, column2, ...: Columns that you want to sort the data by.
ASC: Sorts the data in ascending order (smallest to largest). This is
the default.
DESC: Sorts the data in descending order (largest to smallest).
1. Sorting in Ascending Order (Default)
Example- Retrieves all Customers and sorts them by their name in
ascending order.
SELECT * FROM CUSTOMERS
ORDER BY NAME;
Explanation:
NAME: The result is first sorted alphabetically by the NAME column.
ADDRESS: If two rows have the same NAME, they are sorted by ADDRESS
in descending order.
Group By Clause
The GROUP BY clause is used to group rows that have the same values in
specified columns.
It is used for organizing similar data into groups.
It's often used with aggregate functions such as COUNT (), SUM (),
AVG (), MAX (), and MIN () to perform calculations on each group of
rows.
Syntax-
SELECT column1, aggregate_function(column2)
FROM table_name
WHERE condition
GROUP BY column1, column2, ...,
ORDER BY column1, column2, …;
Example- Write an SQL query to count how many times each customer
appears in the CUSTOMERS table.
SELECT NAME, COUNT(ID) AS CUSTOMERS
FROM CUSTOMERS
GROUP BY NAME;
Example- If you want to know the total amount of the salary on each
customer.
SELECT NAME, SUM(SALARY) AS TotalSalary
FROM CUSTOMERS
GROUP BY NAME;
Example- Write an SQL query to calculate the total salary for each
customer in the CUSTOMERS table whose salary is greater than 3000.
SELECT NAME, SUM(SALARY) AS TotalSalary
FROM CUSTOMERS
WHERE SALARY > 3000
GROUP BY NAME;
Having Clause
ee
The HAVING clause was added to SQL because the WHERE keyword
cannot be used with aggregate functions.
The HAVING clause in SQL is used to filter records based on aggregate
functions ( SUM(), COUNT(), MAX(), MIN(), or AVG() ) after the
GROUP BY clause is applied.
Syntax-
SELECT column1, aggregate_function(column2)
FROM table
WHERE condition
GROUP BY column1
HAVING aggregate_function(column2) condition
ORDER BY column1 ASC|DESC;
Example-
Let's say you want to find all employees whose SALARY is greater than
3000, and you also want to order the results by ID in ascending order.
Example-
Using the CUSTOMERS table below, write an SQL query to find the total
salary for each address. Only include those addresses where the total salary
exceeds 3000.
SELECT ADDRESS, SUM(SALARY) AS SUM_SALARY
FROM CUSTOMERS
GROUP BY ADDRESS
HAVING AVG(SALARY) > 3000;
Explanation:
SELECT ADDRESS, SUM(SALARY): This part selects the ADDRESS
and the total (SUM) of SALARY for each address.
FROM CUSTOMERS: Specifies the table from which to retrieve
data.
GROUP BY ADDRESS: Groups the results by each unique ADDRESS.
HAVING SUM(SALARY) > 3000: Filters the grouped results to
include only those groups where the total salary exceeds 3000.
TOP
n
TOP command is used to specify the number of records to return.
ee
Note − All the databases do not support the TOP clause. For example, MySQL
supports the LIMIT clause to fetch limited number of records while Oracle uses
the ROWNUM command to fetch a limited number of records.
Syntax-
SELECT TOP n column_name(s)
FROM table_name
WHERE condition;
Here, n is the number of rows you want to retrieve.
Syntax-
CREATE TABLE table_name (
column_name datatype NOT NULL, ...
);
Example-
Let, create a new table called CUSTOMERS and adds five columns, three of
which are ID, NAME and AGE, In this we 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)
);
FOR EXISTING TABLE-
Syntax-
ALTER TABLE table_name
ALTER COLUMN column_name datatype NOT NULL;
Example-
If CUSTOMERS table has already been created, then to add a NOT NULL
constraint to the ADDRESS column, the query would be-
ALTER TABLE CUSTOMERS
ALTER COLUMN ADDRESS CHAR (25) NOT NULL;
2. DEFAULT CONSTRAINT-
The DEFAULT constraint provides a default value to a column when the
INSERT INTO statement does not provide a specific value.
Syntax-
CREATE TABLE table_name (
column_name datatype DEFAULT default_value,
column_name datatype,
...
);
Example-
For example, the following SQL creates a new table called CUSTOMERS and
adds five columns. Here, the SALARY column is set to 5000.00 by default, so
in case the INSERT INTO statement does not provide a value for this column,
then by default this column would be set to 5000.00.
Syntax-
ALTER TABLE table_name
ADD CONSTRAINT constraint_name DEFAULT default_value FOR
column_name;
Example-
If the CUSTOMERS table has already been created, then to add a DEFAULT
constraint to the SALARY column, you would write a query-
ALTER TABLE CUSTOMERS
ADD CONSTRAINT DF_SAL DEFAULT 5000.00 FOR SALARY;
Explanation:
DF_SAL: The name of the default constraint (make sure there’s no
space in constraint names).
DEFAULT 5000.00: The default value for the SALARY column.
FOR SALARY: Specifies the column where the default value will be
applied.
Syntax-
ALTER TABLE table_name
DROP CONSTRAINT constraint_name;
Example-
ALTER TABLE CUSTOMERS
DROP CONSTRAINT DF_SAL;
3. UNIQUE CONSTRAINT-
A UNIQUE constraint ensures that all values in a column (or a group
of columns) are unique. This means that no two rows can have the
same value(s) in that column or set of columns.
Syntax-
CREATE TABLE table_name (
column_name datatype UNIQUE,
column_name datatype,
...
);
Example-
Let create a new table called CUSTOMERS and adds five columns. Here, the
AGE column is set to UNIQUE, so that you cannot have two records with the
same age.
CREATE TABLE CUSTOMERS (
ID INT,
NAME VARCHAR (20),
AGE INT UNIQUE,
ADDRESS CHAR (25),
SALARY DECIMAL (18, 2),
);
Syntax-
ALTER TABLE table_name
ADD CONSTRAINT constraint_name UNIQUE (column_name);
Example-
If the CUSTOMERS table has already been created, then to add a UNIQUE
constraint to the AGE column.
ALTER TABLE CUSTOMERS
ADD CONSTRAINT UQ_AGE UNIQUE(AGE);
Syntax-
ALTER TABLE table_name
DROP CONSTRAINT constraint_name;
Example-
ALTER TABLE CUSTOMERS
DROP CONSTRAINT UQ_AGE;
4. CHECK CONSTRAINT-
1. The CHECK constraint ensures that values entered into a column meet a
specific condition:
If the condition is TRUE: The record is allowed and inserted into the
table.
If the condition is FALSE: The record violates the constraint and isn’t
inserted.
Example-
Imagine you have a CUSTOMERS table with a column for age, and you
want to make sure that only customer who are 18 or older can be added
to the table. You can use a CHECK constraint to create this rule.
Syntax-
ALTER TABLE table_name
ADD CONSTRAINT constraint_name CHECK (condition);
Example-
If the CUSTOMERS table has already been created, then to add a CHECK
constraint to AGE column.
ALTER TABLE CUSTOMERS
ADD CONSTRAINT chk_Age CHECK (Age >= 18);
Syntax-
ALTER TABLE table_name
DROP CONSTRAINT constraint_name;
Example-
ALTER TABLE CUSTOMERS
DROP CONSTRAINT chk_Age;
5. PRIMARY KEY-
Syntax 1-
CREATE TABLE table_name (
column1 datatype,
column2 datatype,
...,
PRIMARY KEY (column1, column2)
);
Example-
CREATE TABLE customer (
id INT,
name VARCHAR(100),
age INT,
salary DECIMAL(10, 2),
address VARCHAR(255),
PRIMARY KEY (id, name)
);
Syntax 2-
CREATE TABLE table_name (
column1 datatype,
column2 datatype,
...
CONSTRAINT PK_table_name PRIMARY KEY (column1,column2)
);
Example-
CREATE TABLE customer (
id INT,
name VARCHAR(100),
age INT,
salary DECIMAL(10, 2),
address VARCHAR(255),
CONSTRAINT pk_customer PRIMARY KEY (id, name)
);
C. Alter Table
Syntax 1- Adding a Primary Key to a Single Column
ALTER TABLE table_name
ADD PRIMARY KEY (column_name);
Example-
Assuming the id column should be the primary key:
ALTER TABLE customer
ADD PRIMARY KEY (id);
Syntax 2- Adding a Composite Primary Key
ALTER TABLE table_name
ADD CONSTRAINT constraint_name PRIMARY KEY (column1, column2);
Example-
If you want to create a composite primary key using the id and name
columns, you would use:
ALTER TABLE customer
ADD CONSTRAINT pk_customer PRIMARY KEY (id, name);
Example-
ALTER TABLE customer
DROP CONSTRAINT pk_customer;
6. FOREIGN KEY-
1. CREATE TABLE-
Syntax 1- Creates a foreign key is without using a constraint
name
CREATE TABLE child_table_name (
child_col1 DATATYPE PRIMARY KEY,
child_col2 DATATYPE,
child_col3 DATATYPE,
...
FOREIGN KEY (child_col11, child_col2)
REFERENCES parent_table_name (parent_col1, parent_col2)
);
Example-
-- Creating the CUSTOMER table
CREATE TABLE CUSTOMERS (
id INT PRIMARY KEY,
name VARCHAR(100),
age INT,
salary DECIMAL(10, 2),
address VARCHAR(255)
);
Example-
Let's consider two tables, CUSTOMERS and ORDERS, to explain this:
CUSTOMERS Table (Parent Table): This table stores customer details,
such as id, name, age, salary, and address. The id column is the
primary key, which uniquely identifies each customer.
Example- If the ORDERS table has already been created and the foreign
key has not yet been set, the use the syntax for specifying a foreign key by
altering a table.
3. DROP a Constraint
Syntax-
ALTER TABLE table_name
DROP CONSTRAINT constraint_name;
Syntax-
SELECT column_name(s)
FROM table_name
WHERE column_name LIKE pattern;
Syntax:-
Example-
Example-
select * from students2
union all
select * from students5
3.Intersect- Take the result of two queries and returns
only those rows which are common in both result sets.
It removes duplicate records from the final result set.
Syntax-
SELECT * FROM TABLE1
INTERSECT
SELECT * FROM TABLE2
Example-
select * from students2
intersect
select * from students5
Syntax-
Example-
select * from students2
except
select * from students5