Thanks to visit codestin.com
Credit goes to www.scribd.com

0% found this document useful (0 votes)
17 views37 pages

Simple Queries in SQL

SQL, or Structured Query Language, is a standard language for accessing and modifying relational databases, originally developed at IBM in the 1970s. It is widely used across various database management systems like MySQL, PostgreSQL, and Oracle, and offers advantages such as interactivity, portability, and ease of use without extensive coding. The document also covers SQL commands, data types, and features specific to MySQL, including aggregate functions, JOIN operations, and constraints.

Uploaded by

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

Simple Queries in SQL

SQL, or Structured Query Language, is a standard language for accessing and modifying relational databases, originally developed at IBM in the 1970s. It is widely used across various database management systems like MySQL, PostgreSQL, and Oracle, and offers advantages such as interactivity, portability, and ease of use without extensive coding. The document also covers SQL commands, data types, and features specific to MySQL, including aggregate functions, JOIN operations, and constraints.

Uploaded by

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

SQL

SQL is an acronym of Structured Query Language. It is a


standard language developed and used for accessing and
modifying relational databases.
The SQL language was originally developed at the IBM research
laboratory in San José, in connection with a project developing
a prototype for a relational database management system
called System R in the early 70s.
SQL is being used by many database management systems.
Some of them are:
 MySQL
 PostgreSQL
 Oracle
 SQLite
 Microsoft SQL Server
SQL
Advantages of using SQL
 Interactive Language-This language can be used for
communicating with the databases and receive answers to the
complex questions in seconds.
 Multiple data views-The users can make different views of
database structure and databases for the different users.
 Portability-SQL can be used in the program in PCs, servers,
laptops, and even some of the mobile phones and even on
different DBMS softwares.
 No coding needed-It is very easy to manage the database
systems without any need to write the substantial amount of
code by using the standard SQL.
 Well defined standards-Long established are used by the SQL
databases that is being used by ISO and ANSI. There are no
standards adhered by the non-SQL databases.
SQL
MySQL Features
Open Source & Free of Cost:
It is Open Source and available at free of cost.
 Portability:
Small enough in size to install and run it on any types of Hardware and
OS like Linux, MS Windows or Mac etc.
 Security :
Its Databases are secured & protected with password.
 Connectivity
Various APIs are developed to connect it with many programming
languages.
 Query Language
It supports SQL (Structured Query Language) for handling database.
SQL
Types of SQL Commands

 DDL (Data Definition Language)


To create database and table structure-commands
like CREATE, ALTER , DROP etc.
DML (Data Manipulation Language)
Adding, deleting and modifying data in a
database. Commands like SELECT...., INSERT...,
DELETE..., UPDATE etc.
 DCL (Data Control Language)
Used to manipulate permissions or access rights to
the tables. Commands like GRANT, REVOKE etc.
 Transactional control Language.
Used to control the transactions in a database .
Commands like COMMIT, ROLLBACK,
SAVEPOINT etc.
SQL
Data type in MySQL
 Numeric Data Types:
 INTEGER or INT – up to 11 digit number without decimal.
 SMALLINT – up to 5 digit number without decimal.
 FLOAT (M,D) or DECIMAL(M,D) or NUMERIC(M,D)
Stores Real numbers upto M digit length (including .) with D
decimal places.
e.g. Float (10,2) can store 1234567.89
 Date & Time Data Types:
 DATE - Stores date in YYYY-MM-DD format.
 TIME - Stores time in HH:MM:SS format.
 String or Text Data Type:
 CHAR(Size)
A fixed length string up to 255 characters. (Default is 1)
 VARCHAR(Size)
A variable length string up to 255 characters.
Char, Varchar, Date and Time values should be enclosed with
single (‘ ‘) or double ( “”) quotes in MySQL.
SQL
Database Commands in MySql
Getting listings of available databases
mysql> SHOW DATABASES;
Creating a database-
mysql> CREATE database myschool;
Deleting a database
mysql> DROP database <databasename>;
To remove table
mysql> Drop table <tablename>;
After database creation we can open the database using USE command
mysql> USE myschool;
To show list of tables in opened database
mysql> SHOW TABLES;
Creating a table in the database is achieved with CREATE table statement.
mysql> CREATE TABLE student (lastname varchar(15),firstname varchar(15),
City varchar(20), class char(2));
SQL
The command DESCRIBE is used to view the structure of a table.
mysql> DESCRIBE student;

Database Commands in MySql


To insert new rows into an existing table use the INSERT command:
mysql>INSERT INTO student values(‘Dwivedi’,’Freya’,’Udaipur’,’4’);
We can insert record with specific column only

mysql>INSERT INTO Student(lastname,firstname,city)


VALUES(‘Dwivedi’,’Mohak’,’Udaipur’);

With the SELECT command we can retrieve previously inserted rows:


A general form of SELECT is:

SELECT (field name) FROM table(s)WHERE condition


that the data must satisfy
SQL

• Comparison operators are: < ; <= ; = ; != or <> ; >= ; >


• Logical operators are: AND ; OR ; NOT
• Comparison operator for special value NULL: IS

Selecting rows by using the WHERE clause in the SELECT command


mysql> SELECT * FROM student WHERE class=“4";
Selecting specific columns by listing their names
mysql> SELECT first_name, class FROM student;
Selecting rows with null values in specific column
mysql> SELECT * FROM Student WHERE City IS NULL;
 BETWEEN- to access data in specified range
mysql> SELECT * FROM Student WHERE class between 4 and 6;
SQL
 IN- operator allows us to easily test if the expression in the list of values.
mysql> SELECT * FROM Student WHERE class in (4,5,6);

 Pattern Matching – LIKE Operator


A string pattern can be used in SQL using the following wild card
 % Represents a substring in any length
 _ Represents a single character

Example:
‘A%’ represents any string starting with ‘A’ character.
‘_ _A’ represents any 3 character string ending with ‘A’.
‘_B%’ represents any string having second character ‘B’
‘_ _ _’ represents any 3 letter string.

A pattern is case sensitive and can be used with LIKE operator.


SQL
mysql> SELECT * FROM Student WHERE Name LIKE ‘A%’;
mysql> SELECT * FROM Student WHERE Name LIKE ’%Singh%’;
mysql> SELECT Name, City FROM Student WHERE Class>=8 AND
Name LIKE‘%Kumar%’ ;

mysql> SELECT * FROM Student ORDER BY class;


To get descending order use DESC key word.
mysql> SELECT * FROM Student ORDER BY class DESC;

To display data after removal of duplicate values from specific column.


mysql> SELECT DISTINCT class FROM student;

Deleting selected rows from a table using the DELETE command


mysql> DELETE FROM student WHERE firstname=“Amar";
SQL
To modify or update entries in the table use the UPDATE command
mysql> UPDATE student SET class=“V" WHERE firstname=“Shreya";

Creating Table with Constraints

The following constraints are commonly used in SQL:

NOT NULL -It Ensures that a column cannot have a NULL value
UNIQUE - It 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 - It Uniquely identifies a row/record in another table
CHECK - It Ensures that all values in a column satisfies a specific
condition
DEFAULT - It Sets a default value for a column when no value is specified
SQL
Creating Table with Constraints

mysql> CREATE TABLE Persons(


ID int(3) NOT NULL PRIMARY KEY,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Age int,
City varchar(255) DEFAULT ‘Jaipur',
CONSTRAINT CHK_Person CHECK (Age>=18));

mysql> CREATE TABLE Orders (


OrderID int NOT NULL,
OrderNumber int NOT NULL,
PersonID int,
PRIMARY KEY (OrderID),
FOREIGN KEY (PersonID) REFERENCES Persons(ID));
SQL
Database Commands in MySql

Altering Table

The SQL ALTER TABLE command is used to add, delete or modify


columns in an existing table. You should also use the ALTER TABLE
command to add and drop various constraints on an existing table.
Syntax
The syntax of an ALTER TABLE command to add a new column in
an existing table is as follows.

ALTER TABLE table_name ADD column_name datatype;

The syntax of an ALTER TABLE command to DROP COLUMN in an


existing table is as follows.
SQL
ALTER TABLE table_name DROP COLUMN column_name;

The syntax of an ALTER TABLE command to change the DATA TYPE


of a column in a table is as follows.

ALTER TABLE table_name MODIFY COLUMN column_name datatype;

Altering Table

The syntax of an ALTER TABLE command to add a NOT NULL constraint to a


column in a table is as follows.
ALTER TABLE table_name MODIFY column_name datatype NOT NULL;

The syntax of ALTER TABLE to ADD UNIQUE CONSTRAINT to a


table is as follows.
SQL
ALTER TABLE table_name

ADD CONSTRAINT MyUniqueConstraint UNIQUE(column1, column2...);


The syntax of an ALTER TABLE command to ADD CHECK CONSTRAINT to a
table is as follows.
ALTER TABLE table_name
ADD CONSTRAINT MyUniqueConstraint CHECK (CONDITION);
The syntax of an ALTER TABLE command to ADD PRIMARY KEY
constraint to a table is as follows.

ALTER TABLE table_name


ADD CONSTRAINT MyPrimaryKey PRIMARY KEY (column1, column2...);
The syntax of an ALTER TABLE command to DROP CONSTRAINT from a table
is as follows.
ALTER TABLE table_name
DROP CONSTRAINT MyUniqueConstraint;
SQL
The syntax of an ALTER TABLE command to DROP PRIMARY KEY
constraint from a table is as follows.

ALTER TABLE table_name


DROP CONSTRAINT MyPrimaryKey;
In MySQL, the code is as follows −

ALTER TABLE
Table_name DROP
PRIMARY KEY;
MySQL Order By clause is used to sort the table data in
either Ascending order or Descending order. By default,
data is not inserted into Tables in any order unless we have
an index.
SQL
So, If we want to retrieve the data in any particular order,
we have to sort it by using MySQL Order By statement.

Syntax:-SELECT Column_Names
FROM Table_Name
ORDER BY {Column1}[ASC | DESC] {Column2}[ASC | DESC]

MySQL Order by– e.g.


Suppose we are having student table with following data.
SQL
Now we write the query – select * from student order by class;

Query result will be in ascending order of class. If we do not specify


asc/desc in query then ascending clause is applied by default.

MySQL Order by– e.g.


Suppose we are having student table with following data.
SQL

Now we write the query – select * from student order by class desc;

Query result will be in descending order of class.


SQL
MySQL Order by – e.g.
Suppose we are having student table with following data.

Now we write query–select * from student order by class asc, marks asc;

Query result will be ascending order of class and if same class exists
then ordering will done on marks column (ascending order)
SQL
MySQL Order by– e.g.
Suppose we are having student table with following data.

Now we write query–select * from student order by class asc, marks desc;

Query result will be ascending order of class and if same class exists
then ordering will done on marks column (descending order)
SQL
An aggregate function performs a calculation on multiple values
and returns a single value. For example, you can use the AVG()
aggregate function that takes multiple numbers and returns the
average value of the numbers. Following is the list of aggregate
functions supported by MySQL.

Name Purpose
SUM() Returns the sum of given column.
MIN() Returns the minimum value in the given column.
MAX() Returns the maximum value in the given column.
AVG() Returns the Average value of the given column.
COUNT() Returns the total number of values/ records as per given
column.
SQL
Aggregate Functions & NULL
Consider a table Emp having following records as-
Null values are excluded while (avg) aggregate function is used
Emp
Code Name Sal
E1 Mohak NULL
E2 Anuj 4500
E3 Vijay NULL
E4 Vishal 3500
SQL Queries E5 Anil 4000
Result of query
mysql> Select Sum(Sal) from EMP; 12000
mysql> Select Min(Sal) from EMP; 3500
mysql> Select Max(Sal) from EMP; 4500
mysql> Select Count(Sal) from EMP; 3
mysql> Select Avg(Sal) from EMP; 4000
mysql> Select Count(*) from EMP; 5
SQL
The GROUP BY clause groups a set of rows/records into a
set of summary rows/records by values of columns or
expressions. It returns one row for each group.
We often use the GROUP BY clause with aggregate
functions such as SUM, AVG, MAX, MIN, and COUNT. The
aggregate function that appears in the SELECT clause
provides information about each group.
The GROUP BY clause is an optional clause of the SELECT
statement.
Syntax –
SELECT 1, c2,..., cn, aggregate_function(ci)
FROM table WHERE where_conditions GROUP BY c1 , c2,...,cn;
Here c1,c2,ci,cn are column name
SQL
MySQL group by – e.g.
Suppose we are having student table with following data.

Now we write query–select class from student group by class;

Query result will be unique occurrences of class values, just


similarto use distinct clause like(select distinct class from student).
SQL
MySQL GROUP BY with aggregate functions

The aggregate functions allow us to perform the calculation of a set of


rows and return a single value. The GROUP BY clause is often used with an
aggregate function to perform calculation and return a single value for
each subgroup.

For example, if we want to know the number of student in each class, you
can use the COUNT function with the GROUP BY clause as follows:
Suppose we are having student table with following data.

Now we write query–select class,count(*) from student group by class;


SQL

Query result will be unique occurrences of class values along with counting
of students (records) of each class (sub group).

MySQL GROUP BY with aggregate functions


We are having student table with following data.
SQL
Now we write query–select class,avg(marks) from student group by class;

Query result will be unique occurrences of class values along with average
marks of each class.
MySQL GROUP BY with aggregate functions (with WHERE and ORDER BY clause)
We are having student table with following data.
SQL
Now we write query–
SELECT class,avg(marks) FROM student WHERE class<10
GROUP BY class ORDER BY marks desc;

Query result will be unique occurrences of class values where class<10 along with
average marks of each class(sub group) and descending order of marks.
SQL

The HAVING clause is used in the SELECT statement to specify


filter conditions for a group of rows or aggregates. The HAVING
clause is often used with the GROUP BY clause to filter groups
based on a specified condition. To filter the groups returned by
GROUP BY clause, we use a HAVING clause.
WHERE is applied before GROUP BY, HAVING is applied after
(and can filter on aggregates).

MySQL GROUP BY with aggregate functions & having clause

We are having student table with following data.


SQL

Now we write query–


select class,avg(marks) from student group by class having avg(marks)<90;

Query result will be unique occurrences of class values along with average
marks of each class(sub group) and each class having average marks<90.
SQL
MySQL GROUP BY with aggregate functions & having clause
We are having student table with following data.

Now we write query–


select class,avg(marks) from student group by class having count(*)<3;

Query result will be unique occurrences of class values along with average
marks of each class(sub group) and each class having less than 3 rows.
SQL

Cartesian product (X)/cross joint


Cartesian Product is denoted by X symbol. Let’s say we have two
relations R1 and R2 then the Cartesian product of these two
relations (R1 X R2) would combine each tuple of first relation R1
with the each tuple of second relation R2.

Cartesian product (X) example Mysql query –


Table a and Table b as shown Select * from a,b;
below Select * from a cross join b;
SQL

Degree of Cartesian product is 3 and cardinality is 4=(2 rows of a X 2 rows of b)


SQL

SQL JOINS
❖ JOIN clause combines rows from two or more tables.
❖ creates a set of rows in a temporary table.

Types of SQL JOIN

 EQUI JOIN
oEQUI JOIN is a simple SQL join.
oUses the equal sign(=) as the comparison operator for
the condition

 NON EQUI JOIN

o NON EQUI JOIN uses comparison operator other than


SQL
the equal sign.
o The operators uses like >, <, >=, <= with the condition.

Types of SQL EQUI JOIN

 INNER JOIN
Returns only matched rows from the participating tables.
Match happened only at the key record of participating
tables.

OUTER JOIN
Returns all rows from one table and
Matching rows from the secondary table and
Comparison columns should be equal in both the tables.
SQL
INNER JOIN

The INNER JOIN selects all rows from both participating


tables as long as there is a match between the columns.
An SQL INNER JOIN is same as JOIN clause, combining rows
from two or more tables.

NATURAL JOIN

The SQL NATURAL JOIN is a type of EQUI JOIN and is


structured in such a way that, columns with same name of
associate tables will appear once only.
The associated tables have one or more pairs of identically
named columns.
The columns must be the same data type.

You might also like