Hello everyone, my name is Rishabh Deshpande. Today, we will explore SQL from the basics to advanced concepts in the simplest and easiest way. Let’s dive in!

What is Database and there types ?

A database is a structured collection of data that is stored and managed in a way that allows for easy access, retrieval, and manipulation. Think of it like a digital filing system where information is organized into tables, much like folders in a filing cabinet. Each table holds related data in rows (records) and columns (fields), making it easy to find and use the information you need. Databases are used in a wide range of applications, from websites and apps to business operations, to store everything from customer information to inventory details.

There are two types of database i.e relational and non relatinal types database

RelationalNon-Relational
Use tables to store data in rows and columns
Designed for unstructured or semi-structured data. Includes document, key-value, column-family, and graph databases.(no-SQL)
ex: MySQL, PostgreSQL, Oracle, SQL Server
ex: MongoDB, Cassandra, Redis, CouchDB

Note : We use SQL to work with relational DBMS

Let’s learn basic terminology about SQL


In this, we will learn about basic queries, datatype & SQL commands

we’ll see each every concept in easiest way. Let’s get started.

What is Datatype ?

A data type in SQL (Structured Query Language) is an attribute that specifies the type of data that can be stored in a column of a database table.

Data types help define the operations that can be performed on the data, how it is stored, and how it is retrieved. They are crucial for ensuring data integrity, optimizing storage, and improving query performance.

DATATYPEDESCRIPTIONUSAGE
CHARstring(0-255), can store characters of fixed lengthCHAR(50)
VARCHARstring(0-255), can store characters up to given lengthVARCHAR(50)
BLOBstring(0-65535), can store binary large objectBLOB(1000)
INTinteger(-2,147,483,648 to 2,147,483,647)INT
TINYINTinteger(-128 to 127)TINYINT
BIGINTinteger(-9,223,372,036,854,775,808 to 9,223,372,036,854,775,807)BIGINT
BITcan store x-bit values. x can range from 1 to 64BIT(2)
FLOATDecimal number – with precision to 23 digitsFLOAT
DOUBLEDecimal number – with 24 to 53 digitsDOUBLE
BOOLEANBoolean values 0 or 1BOOLEAN
DATEdate in format of YYYY-MM-DD ranging from 1000-01-01 to 9999-12-31DATE
YEARyear in 4 digits format ranging from 1901 to 2155YEAR

unsigned : TINYINT UNSIGNED (0 To 255)

What are the types of SQL commands

SQL (Structured Query Language) commands are used to interact with and manipulate databases. They are categorized into different types based on their functionality. Here is a detailed breakdown of SQL command types:

Type of SQL CommandFull FormDescriptionCommands
DDLData Definition LanguageDefines and modifies the structure of database objectscreate, alter, rename, truncate, drop
DQLData Query LanguageRetrieves data from the databaseselect
DMLData Manipulation LanguageManipulates data within existing database objectsselect, insert, update, delete
DCLData Control LanguageControls access to data in the databasegrant, revoke
TCLTransaction Control LanguageManages transactions in the databasestart transaction, commit, rollback, etc.

This table provides a clear and organized view of the types of SQL commands, their full forms, descriptions, and examples of each type.

Let’s learn about all basic functions

Before starting we must know that SQL is not case sensitive language. Let’s start the process.

  • CREATE DATABASE : First CREATE DATABASE Example; Highlight the query & execute, Semi colon ; work as full stop in SQL language.
  • DROP DATABASE : Similarly type DROP DATABASE Example ; Highlight the query & execute

CREATE BASIC STRUCTURE OF TABLE : In this we will see basic structure of table, once we done by creating table then we will learn each and every term in detail.

BASIC SYNTAX

USE db_name;

CREATE TABLE table_name (
column_name1 datatype constraint,
column_name2 datatype constraint,
column_name2 datatype constraint
);
CREATE DATABASE college;

USE college;

CREATE TABLE student (
    id INT PRIMARY KEY,
    name VARCHAR(50),
    age INT NOT NULL
);

INSERT INTO student VALUES(1, "Rishabh", 26);
INSERT INTO student VALUES(2, "Rohit", 26
INSERT INTO student VALUES(2, "Manthan", 26);

SELECT * FROM student;

DATATYPE : In SQL, data types define the type of data that can be stored in a column of a table. They are essential for defining the kind of data that a column can hold, ensuring data integrity and optimizing storage.

DATABASE RELATED QUERIES :

CREATE DATABASE IF NOT EXISTS college;

It is best practice to add a database to the server carefully to avoid conflicts with existing databases. To prevent errors if a database already exists, use the following query:

Similarly , We can use the DROP DATABASE IF NOT EXISTS college ;

SHOW DATABASES COMMAND
SHOW TABLES COMMAND

TABLE RELATED QUERIES : It helps us to design (schema) of the table.

CREATE

BASIC SYNTAX
CREATE TABLE table_name (
column_name1 datatype constraint,
column_name2 datatype constraint,
);

INSERT

BASIC SYNATX
INSERT INTO table_name
(colname1, colname2);
VALUES
(col1_v1, col2_v1),
(col1_v2, col2_v2);
CREATE AND INSERT COMMAND

Let’s learn about Keys, contraints & Clause


in this we will see important concept about key, constraints, operators, select & clause.

keys

constraints

select

clause

operators

PRIMARY KEY : It is a column (or set of columns) in a table that uniquely identifies each row. (a unique id) There is only 1 PK & it should be NOT null.

FOREIGN KEY : A foreign key is a column (or set of columns) in a table that refers to the primary key in another table. There can be multiple FKs. FKs can have duplicate & null values.

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

ConstraintDescription
NOT NULLValues cannot be null.
UNIQUEValues cannot match any older value.
PRIMARY KEYUsed to uniquely identify a row.
FOREIGN KEYReferences a row in another table.
CHECKValidates condition for new value.
DEFAULTSets default value if not passed.

FOREIGN KEY : prevent actions that would destroy links between tables.

Customers and Orders. The Orders table will have a foreign key that references the primary key in the Customers table.

EXAMPLE OF FOREIGN KEY
Lets practice different commands and queries.
CREATE DATABASE COLLEGE;
USE COLLEGE ;

CREATE TABLE student (
    rollno INT PRIMARY KEY,
    name VARCHAR(50),
    marks INT NOT NULL,
    grade VARCHAR(1),
    city VARCHAR(20)
);

INSERT INTO student (rollno, name, marks, grade, city)
VALUES
    (101, "anil", 78, "C", "Pune"),
    (102, "bhumika", 93, "A", "Mumbai"),
    (103, "chetan", 85, "B", "Mumbai"),
    (104, "dhruv", 96, "A", "Delhi"),
    (105, "emanuelt", 12, "F", "Delhi"),
    (106, "farah", 82, "B", "Delhi");

SELECT: used to select any data from the database.

Basic Syntax

SELECT col1, col2 FROM table_name;
SELECT * FROM student;
SELECT name, marks FROM student;
SELECT DISTINCT city FROM student ;
we can use clause with select command

Where Clause :

BASIC SYNTAX

SELECT col1, col2 FROM table_name WHERE conditions;
SELECT * FROM student where marks>80;
SELECT * FROM student where city=”mumbai”;
Where ClauseUsing Operators in WHERE
Arithmetic Operators+ (addition), – (subtraction), * (multiplication), / (division), % (modulus)
Comparison Operators= (equal to), != (not equal to), >, >=, <, <=
Logical OperatorsAND, OR, NOT, IN, BETWEEN, ALL, LIKE, ANY
Bitwise Operators& (Bitwise AND), | (Bitwise OR)
SELECT * FROM student where marks>80 and city=”mumbai”;
SELECT * FROM student where marks>80 or city=”mumbai”;
SELECT * FROM student WHERE marks BETWEEN 80 AND 90;
SELECT * FROM student WHERE city in (“pune”,”delhi”);
SELECT * FROM student WHERE city NOT IN (“pune”,”delhi”);

LIMIT Clause : Sets an upper limit on number of (tuples)rows to be returned.

BASIC SYNTAX
SELECT col1, col2 FROM table_name LIMIT number;
SELECT * FROM student LIMIT 3;

ORDER BY Clause : To sort in ascending (ASC) or descending order (DESC)

SELECT col1, col2 FROM table_name ORDER BY col_name(s) ASC;
SELECT * FROM student ORDER BY CITY ASC;
SELECT * FROM student ORDER BY CITY DESC;

AGGREGATE FUNCTION : Aggregate functions perform a calculation on a set of values, and return a single value.

  • COUNT( )
  • MAX( )
  • MIN( )
  • SUM( )
  • AVG( )
SELECT MAX(marks) FROM student;
SELECT MIN(marks) FROM student;
SELECT COUNT(rollno) FROM student;
SELECT AVG(marks) FROM student;

GROUP BY Clause : Groups rows that have the same values into summary rows. It collects data from multiple records and groups the result by one or more column.

NOTE : GROUP BY clause default use ASC order, If we want DESC order then we have to mention in query.

FOR EX : SELECT city, AVG(marks) FROM student ORDER BY city GROUP BY AVG(marks) DESC;

SELECT city, count(rollno) FROM student GROUP BY city;
SELECT city, name ,count(rollno) FROM student GROUP BY city, name;

HAVING Clause : Similar to Where i.e. applies some condition on rows. Used when we want to apply any condition after grouping.

SELECT count(name), city FROM student GROUP BY city HAVING max(marks)>90;

GENERAL ORDER TO WRITE A COMMANDS.

SELECT column(s)
FROM table_name
WHERE condition     -- WHERE apply condition on ROWS.
GROUP BY column(s)
HAVING condition    -- HAVING apply condition on group ROWS.
ORDER BY column(s) ASC;

TABLE RELATED QUERIES

  • UPDATE (to update existing rows)
UPDATE table_name
SET col1 = val1, col2 = val2
WHERE condition;
UPDATE student SET grade = “O” WHERE grade = “A” ;
UPDATE student SET marks = 85 WHERE rollno=105;
  • DELETE (to delete existing rows)
DELETE FROM table_name
WHERE condition;
DELETE FROM student WHERE marks <30;

TABLE RELATED QUERIES :

  • Alter : (to change the schema)
  • ADD COLUMN
Syntax

ALTER TABLE table_name
ADD COLUMN column_name datatype constraint;
ALTER TABLE students ADD COLUMN age INT ;
  • DROP COLUMN
ALTER TABLE table_name
DROP COLUMN column_name;
ALTER TABLE students DROP COLUMN student_age ;
  • RENAME TABLE
ALTER TABLE table_name
RENAME TO new_table_name;
ALTER TABLE students rename to stu ;
  • CHANGE COLUMN (RENAME)
ALTER TABLE table_name
CHANGE COLUMN old_name new_name new_datatype new_constraint;
ALTER TABLE students CHANGE COLUMN age student_age int;
  • TRUNCATE TABLE (to delete table’s data))
TRUNCATE TABLE students;

joins in SQL


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

INNER JOIN

OUTER JOIN

TYPE OF JOINS
  • INNER JOIN : Returns records that have matching values in both tables
Syntax
SELECT column(s)
FROM tableA
INNER JOIN tableB
ON tableA.col_name = tableB.col_name;
CREATE DATABASE example;
USE example;

CREATE TABLE Stu(
id INT PRIMARY KEY,
name VARCHAR(50)
); 
INSERT INTO stu(id,name)
VALUES
(100,"rishabh deshpande"),
(101,"manthan rao"),
(102,"rohit gajbhiye");

CREATE TABLE course(
id INT PRIMARY KEY,
course VARCHAR(50)
);

INSERT INTO course(id,course)
VALUES
(101,"science"),
(102,"mathematics"),
(104,"biology");
SELECT * FROM table1 INNER JOIN table2 ON table1.common_column = table2.common_column;
  • LEFT (OUTER )JOIN : Returns all records from the table A , and the matched records from the table B.
SELECT column(s) FROM tableA LEFT JOIN tableB ON tableA.col_name = tableB.col_name;
  • RIGHT (OUTER) JOIN : Returns all records from the table B, and the matched records from the table A.
SELECT column(s) FROM tableA RIGHT JOIN tableB ON tableA.col_name = tableB.col_name;
  • FULL (OUTER) JOIN :- Returns all records when there is a match in either A or B
.

Similar Posts