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

Simple Queries in SQL

This document provides information about MySQL and simple queries in SQL. It describes that MySQL is an open source database system that uses SQL and has a client-server architecture. It then lists advantages of MySQL like reliability, ease of use, and security. The document explains basic SQL data types, operators, and sample queries using SELECT, DISTINCT, WHERE, BETWEEN, and IN clauses to retrieve data from tables.

Uploaded by

Bighnesh world
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
67 views

Simple Queries in SQL

This document provides information about MySQL and simple queries in SQL. It describes that MySQL is an open source database system that uses SQL and has a client-server architecture. It then lists advantages of MySQL like reliability, ease of use, and security. The document explains basic SQL data types, operators, and sample queries using SELECT, DISTINCT, WHERE, BETWEEN, and IN clauses to retrieve data from tables.

Uploaded by

Bighnesh world
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 27

18-10-2023

MySQL
and
Simple Queries in SQL

 Open source and freely available


 Uses SQL
 Can be easily downloaded from the site www.mysql.org
 MySQL database system works upon client/server architecture (Client makes
request to the Server, Server access database and serves the request)
 It constitutes a MySQL server which runs on a machine containing the
databases and client connect to the server over a network
 My SQL is a multi-user database system

1
18-10-2023

Advantages of MySQL
1) Reliability and performance
2) Easy to use
3) Free and supports SQL
4) Portable/multiplatform support
5) Datatypes
6) Integrity checks
7) Scalability and limits (Has powerful processing capabilities and can handle
large databases containing 60,000 tables and more then 50 million rows.
8) Security (by username and password authentication)
9) Connectivity (Client can connect to MySQL server using several protocols)

Starting MySQL

Workbench

Command line

2
18-10-2023

SQL Datatypes
Each value manipulated by SQL Database has a data type.
A data type specifies the possible values for a variable/identifier, the
operations that can be performed on that type and the way the values of
that type are stored.
The data type of a value associates a fixed set of properties with the value.
In SQL there are three main data types:

• Number
• Date
• Character/String

SQL operators

Arithmetic Operators
Relational Operators are:
Name Description
<, <=, >, >=, =, != (<>)
%, MOD Modulo operator
* Multiplication operator Logical operators are:
+ Addition operator AND (&&), OR (II), NOT(!)
- Minus operator
Unary minus, change the sign
- of the argument
/ Division operator
DIV Integer division

Imp:
• String or group of characters in single/double quotes
• Commands not case sensitive but data is case sensitive.

3
18-10-2023

Sample Relation: Employee

SELECT Statement Basics


The SQL SELECT statement queries data from tables in the database. The statement begins
with the SELECT keyword. The basic SELECT statement has 3 clauses:

• SELECT
• FROM
• WHERE

General format is:


select <col1>, <col2>,…………,<col n>
from <table1>, <table2>
where <condition>

4
18-10-2023

Accessing Database

Command Description
show databases; Displays the list of all the databases.

use <database_name>; Moves to the specified database

select database(); Displays the name of current/active database

show tables; Displays the list of tables within a database

Describe/desc table_name; Displays the structure of the asked table

Selecting content of some columns

 select ename, job, hiredate from employee;


Command to select data of some columns

5
18-10-2023

Ordering of columns
The column headings in the output table of a SQL command is in the same order as that of select
command, nothing changes in original table.

select ename, hiredate, job from employee;

To display data from all the columns:

Syntax: select * from table_name;

Select * from employee;

6
18-10-2023

ALL/DISTINCT Clause
 Select [ALL | DISTINCT] <col list> from
table;
(default is ALL)

JOB
select distinct job
CLERK
from employee; SALESMAN
PRESIDENT
MANAGER
select job from employee; ANALYST

(is equivalent to)


select ALL job from employee;

Distinct eliminates duplicate/redundant rows.

WHERE Clause
 Output based on condition ENAME JOB
Select <col list> SMITH CLERK
JONES MANAGER
from table SCOTT ANALYST
where <cond> ADAMS CLERK
FORD ANALYST

select ename, job ENAME JOB


SMITH CLERK
from employee SCOTT ANALYST
where deptno = 20; ADAMS CLERK
JAMES CLERK
Or FORD ANALYST
select ename, job MILLER CLERK

from employee
where job = 'CLERK' OR job = 'ANALYST'; ENAME JOB
ALLEN SALESMAN
Or WARD SALESMAN
JONES MANAGER
select ename, job
MARTIN SALESMAN
from employee BLAKE MANAGER
CLARK MANAGER
where NOT (job = 'CLERK' || job = 'ANALYST');
KING PRESIDENT
TURNER SALESMAN

7
18-10-2023

BETWEEN Clause
 BETWEEN clause
ENAME HIREDATE
Select ename, hiredate JONES 02-APR-81
from employee BLAKE 01-MAY-81

where sal BETWEEN 2000 AND 3000 CLARK 09-JUN-81


SCOTT 19-APR-87
(Note: BETWEEN includes both the lower and upper range)
FORD 03-DEC-81

ENAME HIREDATE
Select ename, hiredate
SMITH 17-DEC-80
from employee ALLEN 20-FEB-81

where sal NOT BETWEEN 2000 AND 3000 WARD 22-FEB-81


MARTIN 28-SEP-81
KING 17-NOV-81
TURNER 08-SEP-81
ADAMS 23-MAY-87
JAMES 03-DEC-81
MILLER 23-JAN-82

IN Clause
Condition to select from a set/list – IN clause
select ename ENAME
from employee SMITH
JONES
where job IN ('CLERK', 'ANALYST', 'MANAGER');
BLAKE
CLARK
OR SCOTT
ADAMS
JAMES
select * from employee FORD
where job NOT IN ('CLERK', 'ANALYST', 'MANAGER'); MILLER

EMPNO ENAME JOB MGR HIREDATE SAL COMM DEPTNO


7499 ALLEN SALESMAN 7698 20-FEB-81 1600 300 30
7521 WARD SALESMAN 7698 22-FEB-81 1250 500 30
7654 MARTIN SALESMAN 7698 28-SEP-81 1250 1400 30
7839 KING PRESIDENT 17-NOV-81 5000 NULL 10
7844 TURNER SALESMAN 7698 08-SEP-81 1500 0 30

8
18-10-2023

NULL Values (through is/is not operator)


 NULL values
select * from employee select * from employee
where comm is NULL; where comm is NOT NULL;
EMPNO ENAME JOB MGR HIREDATE SAL COMM DEPTNO
7369 SMITH CLERK 7902 17-DEC-80 800 NULL 20
7566 JONES MANAGER 7839 02-APR-81 2975 NULL 20
7698 BLAKE MANAGER 7839 01-MAY-81 2850 NULL 30
7782 CLARK MANAGER 7839 09-JUN-81 2450 NULL 10
7788 SCOTT ANALYST 7566 19-APR-87 3000 NULL 20
7839 KING PRESIDENT NULL 17-NOV-81 5000 NULL 10
7876 ADAMS CLERK 7788 23-MAY-87 1100 NULL 20
7900 JAMES CLERK 7698 03-DEC-81 950 NULL 30
7902 FORD ANALYST 7566 03-DEC-81 3000 NULL 20
7934 MILLER CLERK 7782 23-JAN-82 1300 NULL 10

EMPNO ENAME JOB MGR HIREDATE SAL COMM DEPTNO


7499 ALLEN SALESMAN 7698 20-FEB-81 1600 300 30
7521 WARD SALESMAN 7698 22-FEB-81 1250 500 30
7654 MARTIN SALESMAN 7698 28-SEP-81 1250 1400 30
7844 TURNER SALESMAN 7698 08-SEP-81 1500 0 30

Handling NULL

ifnull(field, 'text')

Replaces null with


specified text for a
particular field, while
displaying table's
content

9
18-10-2023

Simple calculations

 Display of simple calculations ENAME SAL+COMM


Select ename, sal+comm ALLEN 1900

from employee WARD 1750


MARTIN 2650
where comm is not NULL;
TURNER 1500

ENAME SAL*12
 Displaying Annual salary of dept
20 SMITH 9600
JONES 35700
select ename, sal*12 SCOTT 36000
from employee ADAMS 13200
where deptno=20; FORD 36000

Simple calculations

Simple calculations can be done on command prompt.

Dual is a table with one row and one column without any data, can be
used for obtaining result of some calculations and for using some
functions.

10
18-10-2023

COLUMN alias
Select ename NAME, sal*12 "ANNUAL SALARY"
from employee;
OR
Select ename NAME, sal*12 AS "ANNUAL SALARY"
from employee; NAME ANNUAL SALARY
SMITH 9600
ALLEN 19200
WARD 15000
JONES 35700
MARTIN 15000
BLAKE 34200
CLARK 29400
SCOTT 36000
KING 60000
TURNER 18000
ADAMS 13200
JAMES 11400
FORD 36000
MILLER 15600

TEXT in a query

 Placing text in output


select ename, 'works in', deptno
from employee
where deptno = 10;

ENAME 'WORKSIN' DEPTNO


CLARK works in 10
KING works in 10
MILLER works in 10

11
18-10-2023

PATTERN Matching
 Pattern matching
% matches any substring (0 onwards)
_ matches exactly one character (no zero even)

select * from emp select * from emp


where ename like 'A%'; where ename like '_ _ A%';
EMPNO ENAME JOB MGR HIREDATE SAL COMM DEPTNO
7499 ALLEN SALESMAN 7698 20-FEB-81 1600 300 30
7876 ADAMS CLERK 7788 23-MAY-87 1100 NULL 20

EMPNO ENAME JOB MGR HIREDATE SAL COMM DEPTNO


7698 BLAKE MANAGER 7839 01-MAY-81 2850 NULL 30
7782 CLARK MANAGER 7839 09-JUN-81 2450 NULL 10
7876 ADAMS CLERK 7788 23-MAY-87 1100 NULL 20

Command to display all the records not having a character 'S' ??

Write SQL queries for displaying:

Q. Details of all those employees whose names are neither starting


with ‘A’ nor ends with ‘R’.

Q. Details of all those employees who joined in the year 1981.

Q. Details of all those employees who joined after 1981.

Q. Details of all those employees whose name contains an alphabet ‘N’.

12
18-10-2023

Sorting output
ENAME HIREDATE
 Sorting Output –
ADAMS 23-MAY-87
Order by clause (ASC/DESC) SCOTT 19-APR-87
Select ename, hiredate FORD 03-DEC-81

from emp JONES 02-APR-81


SMITH 17-DEC-80
where deptno = 20
order by hiredate desc; DEPTNO ENAME
30 ALLEN
30 BLAKE
30 JAMES
30 MARTIN
30 TURNER
30 WARD
Select deptno, ename 20 ADAMS
20 FORD
from emp 20 JONES
order by deptno desc, ename; 20 SCOTT
20 SMITH
10 CLARK
(Note: default is ASC) 10 KING
10 MILLER

Order of combining clauses

SELECT column list


FROM <table name>
WHERE <predicate>
GROUP BY <column name(s)>
HAVING <search condition>
ORDER BY column_name;

13
18-10-2023

A function is used to perform some particular task


Functions can be applied to work on single or multiple records (rows) of a table.
Depending on their application in one or multiple rows, SQL functions are:
• Single Row Functions
• Multiple Row Functions/Aggregate functions.

NUMERIC Functions
Function Description
MOD() Returns remainder
select mod(100, 7);
2
POWER()/ Returns first argument raised to the power second
POW() select pow(2, 5);
32
ROUND() Rounds to specified no of decimal place or to integer, 2nd input is optional
select (22/7);
3.1429
select round(22/7, 3);
3.143
select round(22/7);
3

14
18-10-2023

NUMERIC Functions
Function Description
SQRT() Returns square root of positive input
select sqrt(6.25);
2.5
select sqrt(11);
3.3166247903554
select sqrt(4);
2
select sqrt(-4);
NULL
TRUNCATE() Truncates to specified number of decimal place or to integer, no
rounding, 2nd input is not optional
select truncate(22/7, 3);
3.142

STRING Functions

Function Description Example with output


UCASE(string) converts string into uppercase. SELECT UCASE("Computer Science");
OR Output:
UPPER(string) COMPUTER SCIENCE

LOWER(string) converts string into lowercase. SELECT LOWER("Computer Science");


OR Output:
LCASE(string) computer science

MID(string, pos, n) Returns a substring of size n SELECT MID("Information", 3, 4);


OR starting from the specified Output:
SUBSTRING(string, pos, n) position (pos) of the string. If n is form
OR not specified, it returns the
SUBSTR(string, pos, n) substring from the position pos SELECT MID("Information",7);
till end of the string Output:
ation

15
18-10-2023

STRING Functions
Function Description Example with output
LENGTH(string) Return the number of characters in SELECT LENGTH("Information");
the specified string Output:
11

LEFT(string, N) Returns N number of characters from SELECT LEFT("Computer", 4);


the left side of the string Output:
Comp

RIGHT(string, N) Returns N number of characters from SELECT RIGHT("SCIENCE", 3);


the right side of the string. Output:
NCE

INSTR(string, Returns the position of the first SELECT INSTR("Information", "ma");


substring) occurrence of the substring in the Output:
given string. Returns 0, if the substring 6
is not present in the string

STRING Functions
Function Description Example with output
LTRIM(string) Returns the given string after SELECT LENGTH(“ DELHI”), LENGTH(LTRIM(“ DELHI”));
removing leading white Output:
space characters +--------+--------+
|7|5|
+--------+--------+

RTRIM(string) Returns the given string after SELECT LENGTH(“PEN “), LENGTH(RTRIM(“PEN “));
removing trailing white space Output:
characters. +--------+--------+
|5|3|
+--------+--------+

TRIM(string) Returns the given string after SELECT LENGTH(“ MADAM “), LENGTH(TRIM(“ MADAM “));
removing both leading and Output:
trailing white space +--------+--------+
characters |9|5|
+--------+--------+

16
18-10-2023

STRING Functions

Function Description
CONCAT() Returns concatenated string
select concat('abc', "pqr", '123');
abcpqr123
SUBSTRING()/ Returns substring
SUBSTR() select substr('abcdefgh', 2, 4);
bcde

DATE and TIME Functions


Function Description Example with output

NOW() It returns the current system SELECT NOW();


date and time Output:
2019-07-11 19:41:17

DATE() It returns the date part from SELECT DATE(NOW());


the given date/time Output:
expression. 2019-07-11

MONTH(date) It returns the month in SELECT MONTH(NOW());


numeric form from the date Output:
7

MONTHNAME(date) It returns the month name SELECT MONTHNAME("2003-11-28");


from the specified date. Output:
November

17
18-10-2023

DATE and TIME Functions


Function Description Example with output

YEAR(date) It returns the year from the SELECT YEAR("2003-10- 03");


date. Output:
2003

DAY(date) It returns the day part from the SELECT DAY("2003-03- 24");
date Output:
24

DAYNAME(date) It returns the name of the day SELECT DAYNAME("2019-07-11");


from the date Output:
Thursday

DATE and TIME Functions

Function Description
CURDATE()/ Returns current date
CURRENT_DATE()/
CURRENT_DATE
DATE() Returns date part of a date or date-
time input
MONTH() Returns month of an input date
YEAR() Returns year of an input date
NOW() Returns the time at which now
executes
SYSDATE() Returns the current date and time

18
18-10-2023

Aggregate/Statistical function
 Statistical function
• avg
• sum General syntax:
• min Function ([DISTINCT | ALL] field/parameter)
• max from table_name;
• count
• count(*)
SUM(SAL)
Select sum(sal)
from emp 10875
where deptno = 20;

Select avg(sal) AVG(SAL)


from emp
2175
where deptno = 20;

Aggregate/Statistical function

Select min(sal), max(sal) MIN(SAL) MAX(SAL)


from emp
800 3000
where deptno = 20;

Select count(DISTINCT job ) COUNT(DISTINCTJOB)


from emp; 5

Select count(*) COUNT(*)


From emp;
(counts total number of rows/ 14
employees of the table)

SQL command to find the oldest/latest employee of from the table ??

19
18-10-2023

Single Row vs Multiple Row Function

Single Row Function Multiple Row Function


1. It operates on a single row at a 1. It operates on groups of rows.
time. 2. It returns one result for a group of
2. It returns one result per row. rows.
3. It can be used in Select, Where, 3. It can be used in the select clause
and Order by clause. only.
4. Math, String and Date functions 4. Max(), Min(), Avg(), Sum(), Count()
are examples of single row functions. and Count(*) are examples of
multiple row functions.

Schema diagram of database CARSHOWROOM

20
18-10-2023

A database called CARSHOWROOM having the schema as shown above.


It has the following four relations:
1) INVENTORY: Stores name, price, model, year of manufacturing, and fuel type
for each car in inventory of the showroom
2) CUSTOMER: Stores customer id, name, address, phone number and email for
each customer
3) SALE: Stores the invoice number, car id, customer id, sale date, mode of
payment, sales person’s employee id and selling price of the car sold
4) EMPLOYEE: Stores employee id, name, date of birth, date of joining,
designation and salary of each employee in the showroom

21
18-10-2023

Example
Calculate GST as 12 per cent of Price and display the result after rounding it off to one decimal
place.

SELECT ROUND(12/100*Price,1) "GST" FROM INVENTORY;

Add a new column FinalPrice to the table inventory which will have the value as sum of Price and
12 per cent of the GST.

ALTER TABLE INVENTORY ADD(FinalPrice Numeric(10,1));


UPDATE INVENTORY SET FinalPrice=Price+Round(Price*12/100,1);

Calculate and display the amount to be paid each month (in multiples of 1000) which is to be
calculated after dividing the FinalPrice of the car into 10 instalments

After dividing the amount into EMIs, find out the remaining amount to be paid immediately, by
performing modular division.

SELECT CarId, FinalPrice, ROUND(FinalPriceMOD(FinalPrice,1000)/10,0) "EMI",


MOD(FinalPrice,10000) "Remaining Amount" FROM INVENTORY;

22
18-10-2023

Example
Let us now add a new column Commission to the SALE table. The column Commission should have a
total length of 7 in which 2 decimal places to be there.

ALTER TABLE SALE ADD(Commission Numeric(7,2));

Let us now calculate commission for sales agents as 12% of the SalePrice, Insert the values to the
newly added column Commission and then display records of the table SALE where commission >
73000.

UPDATE SALE SET Commission=12/100*SalePrice;

Display InvoiceNo, SalePrice and Commission such that commission value is rounded off to 0.

SELECT InvoiceNo, SalePrice, Round(Commission,0) FROM SALE;

Example
SELECT LOWER(CustName), UPPER(Email) FROM CUSTOMER;

SELECT LENGTH(Email), LEFT(Email, INSTR(Email, "@")-1) FROM CUSTOMER;

SELECT MID(Phone,3,4) FROM CUSTOMER WHERE CustAdd like ‘%Rohini%’;

SELECT TRIM(".com" from Email) FROM CUSTOMER;

SELECT * FROM CUSTOMER WHERE Email LIKE "%yahoo%";

SELECT DAY(DOJ), MONTH(DOJ), YEAR(DOJ) FROM EMPLOYEE;

SELECT DAYNAME(DOJ), DAY(DOJ), MONTHNAME(DOJ), YEAR(DOJ) FROM EMPLOYEE


WHERE DAYNAME(DOJ)!='Sunday';

23
18-10-2023

24
18-10-2023

25
18-10-2023

create table department


(deptno integer primary key,
dname varchar(20) not null,
dloc varchar(20));

insert into department values


(10, 'ACCOUNTING', 'NEW YORK'),
(20, 'RESEARCH', 'DALLAS'),
(30, 'SALES', 'CHICAGO'),
(40, 'OPERATIONS', 'BOSTON');

create table employee


(empno integer primary key,
ename varchar(50) not null,
job varchar(20),
mgr integer references employee(empno),
hiredate date,
sal integer check (sal between 0 and 10000),
comm integer,
deptno integer references department(deptno));

INSERT INTO EMPLOYEE


(empno, ename, job, mgr, hiredate, sal, deptno)
VALUES(7369, 'SMITH', 'CLERK', 7902, '1980-12-17', 800, 20);

26
18-10-2023

INSERT INTO EMPLOYEE VALUES


(7499, 'ALLEN', 'SALESMAN', 7698, '1981-02-20', 1600, 300, 30),
(7521, 'WARD', 'SALESMAN', 7698, '1981-02-22', 1250, 500, 30),
(7566, 'JONES', 'MANAGER', 7839, '1981-04-02', 2975, NULL, 20),
(7654, 'MARTIN', 'SALESMAN', 7698, '1981-09-28', 1250, 1400, 30),
(7698, 'BLAKE', 'MANAGER', 7839, '1981-05-01', 2850, NULL, 30)
(7782, 'CLARK', 'MANAGER', 7839, '1981-06-09', 2450, NULL, 10),
(7788, 'SCOTT', 'ANALYST', 7566, '1987-04-19', 3000, NULL, 20),
(7839, 'KING', 'PRESIDENT', NULL, '1981-11-17', 5000, NULL, 10),
(7844, 'TURNER', 'SALESMAN', 7698, '1981-09-08', 1500, 0, 30),
(7876, 'ADAMS', 'CLERK', 7788, '1987-05-23', 1100, NULL, 20),
(7900, 'JAMES', 'CLERK', 7698, '1981-12-03', 950, NULL, 30),
(7902, 'FORD', 'ANALYST', 7566, '1981-12-03', 3000, NULL, 20),
(7934, 'MILLER', 'CLERK', 7782, '1982-01-23', 1300, NULL, 10);

27

You might also like