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

SQL NOTES nidhi

Uploaded by

Nidhi Kushwaha
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)
17 views

SQL NOTES nidhi

Uploaded by

Nidhi Kushwaha
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/ 35

SQL NOTES

BY- NIDHI KUSHWAHA

𝐃𝐚𝐭𝐚
 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.

Relational Database Management


System(RDBMS)
 It is a type of DBMS that manage relational database.
 It helps to store, organize and retrieve data efficiently. RDBMS softwares
are MySQL, PostgreSQL, SQL Server, and Oracle.

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.

Commonly used Data Types are-


A. String Datatypes- It stores text strings.

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.

B. Numeric Datatypes- These datatypes store numbers, both integer and


floating-point number.

1. INT-
 Used for storing whole numbers without decimal.

2. FLOAT-
 Used for storing numbers without decimal.
 Float gives approximate value while performing calculations.

3. Decimal (P, S)-


 Used to store numbers with a fixed number of decimal places.
 Decimal gives exact value.
 Total range of digits can be 1-38. (Precision-P)
 Range after decimal should be 0-30. (Scale-S)
C. Date and Time Datatypes- These datatypes stores date and time.

 DATE- Stores date values (Format:- YYYY-MM-DD).

 TIME- Stores time values (Format:- HH:MM:SS).

 DATETIME- Stores both date and time values (Format:- YYYY-MM-DD


HH:MM:SS).

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

 SQL commands are instructions.


 It is used to communicate with the database to perform tasks, functions
and queries of data.
 There are five types of SQL commands.
1. Data Definition Language (DDL)- DDL commands are used to define and
manage the structure or schema of a database.

2. Data Manipulation Language(DML)- DML commands are used to


manipulate or manage the data stored in a database. These commands
are specifically designed to modify the actual data stored in the
database.

3. Data Control Language(DCL)- DCL commands are specifically designed


for managing security and permissions within a database.

4. Transaction Control Language(TCL)- TCL commands manages


transactions in a database.

5. Data Query Language(DQL)- DQL commands are used primarily for


querying and retrieving data from a database.
Create Command

 Create command is used for creating a new database and a table.

1. Create a Database-

Syntax-

CREATE DATABASE database_name;

Example-

CREATE DATABASE SalesDB;

USE DATABASE- It is used to select a database from a list of database


available in the system.

Syntax-

USE database_name;

Example-

USE SalesDB;
2. Create Table-

Syntax-

CREATE TABLE table_name(


column1 datatype,
column2 datatype,
column3 datatype,
.....
columnN datatype,
);

Example-

CREATE TABLE CUSTOMERS(


ID INT,
NAME VARCHAR (20),
AGE INT,
ADDRESS CHAR (25) ,
SALARY DECIMAL (18, 2),
);
Drop Command

 DROP command is used to permanently remove the entire table or


database, along with its structure and the data.
 DROP command cannot be rolled back. Once executed, the data and
structure cannot be recovered unless there's a backup.

1. Drop a Database-

Syntax-

DROP DATABASE database_name;

Example-

DROP DATABASE SalesDB;

2. Drop a Table-

Syntax-

DROP TABLE table_name;

Example-
DROP TABLE CUSTOMERS;
Insert Command

 INSERT command is used to insert new records into a table.

1. Insert data into all columns-

Syntax-

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


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

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-

INSERT INTO table_name VALUES (value1, value2, value3, ...)

Example-

INSERT INTO CUSTOMERS VALUES (3, 'Kaushik', 23, 'Kota', 2000.00);


INSERT INTO CUSTOMERS VALUES (4, 'Chaitali', 25, 'Mumbai', 6500.00);
INSERT INTO CUSTOMERS VALUES (5, 'Hardik', 27, 'Bhopal', 8500.00);
INSERT INTO CUSTOMERS VALUES (6, 'Muffy', 24, 'Indore', 10000.00 );

2. Insert data into specific columns-

Syntax-
INSERT INTO table_name (column1, column2, column3, ...)
VALUES (value1, value2, value3, ...);

Example-

INSERT INTO CUSTOMERS (ID, NAME, SALARY)


VALUES (7, 'Bharti', 12000.00 );
Select Command

 The SELECT command is used to retrieve/fetch the data from a database.

1. Select all columns/fields-

To select all columns from a table, you can use the asterisk (*):

Syntax-

SELECT * FROM table_name;

Example-

SELECT * FROM CUSTOMERS;

2. Select specific columns/fields-

Syntax-

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

Example-
To fetch the ID, Name and Salary fields of the customers available in
CUSTOMERS
table.
SELECT ID, NAME, SALARY FROM CUSTOMERS;

Where Clause

 WHERE clause is used to filter records based on specified/given


conditions. It allows you to retrieve only those rows that meet certain
criteria.

Syntax-

SELECT column1, column2, ...


FROM table_name
WHERE condition;

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.

Different types of SQL operators:

1. Arithmetic Operators-
 Used to perform mathematical operations on numeric values.

Common operators-

a) Addition (+): Adds two values.

Example- Let a=10 and b=5

SELECT 10 + 5;

(a+b will give the result as 15)

b) Subtraction (-): Subtract one value from another.

Example- Let a=10 and b=5

SELECT 10 - 5;

(a-b will give the result as 5)


c) Multiplication (x): Multiplies two values.

Example- Let a=10 and b=5

SELECT 10 * 5;

(a*b will give the result as 50)

d) Division (/): Divides one value by another.


Example- Let a=10 and b=5

SELECT 10 / 5;

(a/b will give the result as 2)

e) Modulus (%): Returns the remainder of division.

Example- Let a=10 and b=5

SELECT 10 % 5;

(a%b will give the result as 0)


2. Comparison Operators-
 Used to compare two values.

Common operators-

a) Equal (=): Checks if two values are equal, if yes then condition

Example-
becomes true.

SELECT * FROM CUSTOMERS WHERE ID = 3;

b) Not equal to (!= or <>): Checks if two values are not equal, if yes then

Example-
condition becomes true.

SELECT * FROM CUSTOMERS WHERE SALARY != 2000;

Example-
c) Greater than (>): Checks if one value is greater than another.

SELECT * FROM CUSTOMERS WHERE SALARY > 2000;


Example-
d) Less than (<): Checks if one value is less than another.

SELECT * FROM CUSTOMERS WHERE SALARY < 2000;

e) Greater than or Equal To (>=): Checks if one value is greater than or

Example-
equal to another.

SELECT * FROM CUSTOMERS WHERE SALARY >= 2000;

f) Less than or Equal To (<=): Checks if one value is less than or equal to

Example-
another.

SELECT * FROM CUSTOMERS WHERE SALARY <= 2000;


3. Logical Operators-
 Used to combine multiple conditions.

Common Operators-

Syntax-
a) AND: Returns true if all conditions are true.

SELECT column1, column2, ...


FROM table_name
WHERE condition1 AND condition2;

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.

SELECT ID, NAME, SALARY


FROM CUSTOMERS
WHERE SALARY > 2000 AND age < 25;

Syntax-
b) OR: Returns true if any condition is true.

SELECT column1, column2, ...


FROM table_name
WHERE condition1 OR condition2;

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;

c) NOT: It is used to negate a condition. This operator is used to exclude


certain records means it helps you find records where the condition is

Syntax-
not true.

SELECT column1, column2, ...


FROM table_name
WHERE NOT condition;

Example-
To fetch the ID, Name and Salary fields from the CUSTOMERS table, whose
salary is not 2000.

SELECT ID, NAME, SALARY


FROM CUSTOMERS
WHERE NOT SALARY = 2000;
IN Operator

 IN operator checks whether a value matches any value in a given list.


 The IN operator works similarly to using multiple OR conditions.

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.

SELECT ID, NAME, ADDRESS


FROM CUSTOMERS
WHERE ADDRESS IN('DELHI','BHOPAL','MUMBAI');
BETWEEN Operator

 BETWEEN operator checks whether a value is within a range of values.


 It can be used with various data types such as numbers, dates, and
strings.
 BETWEEN operator in SQL is similar to using the AND operator.

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 ID, NAME, AGE


FROM CUSTOMERS
WHERE AGE BETWEEN 24 AND 27;
Example-
Retrieve the details from CUSTOMERS table WHERE SALARY BETWEEN 2000
AND 10000.

SELECT *
FROM CUSTOMERS
WHERE SALARY BETWEEN 2000 AND 10000;
NUL
 NULL values represent missing value or unknown data.
 NULL is neither a space or zero(0).
 NULL can’t be compared with any value/anything, not even to another
NULL.

Example-
If you have a CUSTOMERS table and you want to insert a record for Bharti
without providing her age and address:
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.

INSERT INTO CUSTOMERS (ID, NAME,AGE,ADDRESS,SALARY)


VALUES (8, 'Rahul',25,'Delhi', NULL);
IS NULL
 This condition is used to check whether a column contains a NULL value.

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;
DISTIN

 DISTINCT keyword is used to return only unique values in a result set by


removing duplicate rows from the query results.

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.

Alia

 In SQL, an alias is a temporary name given to a table or column, mainly


used to make queries more readable and concise.
 Aliases are temporary. They only exist for the duration of the query in
which they are used.
 Aliases are created using the AS keyword, but using AS is optional.

Syntax-
The basic syntax of a table alias is as follows-
SELECT column_name AS alias_name
FROM table_name
WHERE [condition];

The basic syntax of a column alias is as follows.


SELECT column_name AS alias_name
FROM table_name
WHERE [condition];
Example-
Let's say we want to retrieve data from both the CUSTOMERS and ORDERS
tables so we'll use aliases for better readability.

Table 1 − CUSTOMERS Table is as follows.

Table 2 − ORDERS Table is as follows.

Example Query with Table Aliases:


We will assign aliases to the tables CUSTOMERS and ORDERS to make the query
shorter and easier to read.
SELECT C.NAME, O.AMOUNT ,O.DATE
FROM CUSTOMERS AS C, ORDERS AS O
WHERE C.ID = O.CUSTOMER_ID;
Here,
 C is the alias for the CUSTOMERS table.
 O is the alias for the ORDERS table.
 We are selecting the NAME column from the CUSTOMERS table, and the
AMOUNT and DATE columns from the ORDERS table.
 The JOIN condition is C.ID = O.CUSTOMER_ID, which connects the two
tables based on the ID in the CUSTOMERS table and the CUSTOMER_ID
in the ORDERS table.

Result-

Example Query with Column Aliases:

SELECT C.NAME AS CUSTOMER_NAME , O.AMOUNT AS ORDER_AMOUNT,


O.DATE AS ORDER_DATE
FROM CUSTOMERS AS C, ORDERS AS O
WHERE C.ID = O.CUSTOMER_ID;

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.

Here are the ways to create aliases without the AS keyword:

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.

SELECT C.NAME CUSTOMER_NAME , O.AMOUNT ORDER_AMOUNT


FROM CUSTOMERS C, ORDERS O
WHERE C.ID = O.CUSTOMER_ID;
Create a clone table/duplicate
table/backup table
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.

A) Copy all Columns into a New Table-


Syntax-
SELECT * INTO new_table
FROM existing_table
WHERE condition(Optional);

Example-
SELECT * INTO BACKUP_CUSTOMERS
FROM CUSTOMERS
WHERE ADDRESS = 'Delhi';

SELECT * FROM BACKUP_CUSTOMERS;

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;

SELECT * FROM BACKUP_CUSTOMERSDETAIL;

2. INSERT INTO SELECT-


 INSERT INTO SELECT is used to copy data or transfer data from one
table to another table that already exists in your database.
 The target table must have a structure (columns) that matches or is
compatible with the source table (the table from which you're
copying data).
A) Copy only Selected or Few Columns
from one Table to Another Table-

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.

INSERT INTO BACKUP_CUSTOMERS(ID, NAME, AGE, ADDRESS, SALARY)


SELECT ID, NAME, AGE, ADDRESS, SALARY
FROM CUSTOMERS
WHERE AGE > 30;

SELECT * FROM BACKUP_CUSTOMERS;

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';

SELECT * FROM BACKUP_CUSTOMERS;

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy