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

SQL Básico en Ciencia de Datos

Para los que están en el mundo de Data Science, aprendiendo SQL básico estas notas les pueden ayudar.

Uploaded by

Grace Alejandra
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)
24 views37 pages

SQL Básico en Ciencia de Datos

Para los que están en el mundo de Data Science, aprendiendo SQL básico estas notas les pueden ayudar.

Uploaded by

Grace Alejandra
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

TOPICS covered

1 Order By
2 Limit
3 Aliases
4 Aggregate functions
M IN C MAX I COUNTS I SUM C I Ava C 1

ROUND I

5
String manipulation functions
LENGTH 7 UPPERC I LOWER I 7 SUBSTRINGS

MID C LOCATE C I REPLACE TRIM C I

CON CAT I

6 DATE functions
NOW CI CORDATE I CURT INEC DATE

YEARS I MONTH I DAYS I EXTRACT

DATE ADD C I DATE SU BC I DATED FFC

DATE FORM ATC

7 NULL functions
IS NULL C IS NOT NULL C COALESCE C

IF NULL I NULL IFC I

8 NUMBER functions
AB SC CE ICC I FLOOR C I ROUND C J M DC

POWERED SORT C D RAN DC


ORDER BY Keyword
The ORDER BY keyword is used to sort the

result set in ascending or descending order

By default it is ascending order If we

want it in descending order we use the


DESC keyword

syntax
SELECT Column 1 column 2

FROM table name

ORDER BY Column 1 Columns ASC DESC

Example ASC Example


SELECT
FROM Customers
ORDER BY Country
DESC Example
SELECT
FROM Customers
ORDER BY Country DESC

ORDER BY Multiple Columns Example

SELECT
FROM Customers
ORDER BY Country City
R

SELECT
FROM Customers
ORDER BY Country ASC City DESC
SQL LIMIT Clause

The SQL LIMIT Clause is used to specify


the number of records to return

In MS ACCESS We use TOP ORACLE

USES ROW NUM

Syntax
SELECT Column 1 Column 2

FROM C table name

LIMIT number

Example
SELECT
FROM Customers

LIMIT 3

Cor
SELECT
FROM customers

WHERE Country India

LIMIT 3
in MS ACCESS ORACLE
Equivalent Examples
MS ACCESS Example
SELECT TOP 3

FROM Customers

WHERE country India

ORACLE Example
SELECT

FROM Customers
WHERE country India AND ROWNUM E3
SQL Aliases

SQL aliases are used to give a table or a

column in a table a temporary name

Aliases are often used to make column names

more readable

An alias only exists for the duration of the

query
Alias column syntax
SELECT Column name As alias name

FROM table name

Alias Table syntax


SELECT Column 1 column 2

FROM table name As alias name

Examples
SELECT ID AS Customer ID

Custmer name AS Customer

FROM customers

Of Alias name consists of space It needs to

be enclosed in double quotes or square


brackets
SELECT ID AS Customer ID

Custmer name As contact Person

FROM customers

er
SELECT ID AS Customer ID

Custmer name As contact person

FROM customers

SELECT O Order JD O Order Dale C Customer name

FROM Customers AS C Orders AS 0

WHERE C Customer name XXX AND

C Customer JD O Customer JD

Aliases can be useful when

There are more than one table involved


in a query

Functions are used in the query


Column names are big and not very readable
Two or more columns are combined together
SQL Aggregate functions

SQL MI NC and MaxCl Functions

The mine function returns the smallest

value of the selected column

The Max Cl function returns the largest


value of the selected column

MI NC syntax
SELECT MIN Column name

From C table name

WHERE Condition

MAX C syntax
SELECT MAX Column name

From table name

WHERE Condition

Examples
SELECT MIN Case As min age

From customers

SELECT MAX Case As Man age

From customers
SQL Count C Ava C and SUM C Functions

The counter function returns the number

of rows that matches a specified criteria

The Ava C 7 function returns the average

Value of the numerical column

The sonic I function returns the total sum

of a numerical column

Count C I syntax
SELECT Count Column name

FROM table name

WHERE condition

AVG I syntax
SELECT AVG Column name

FROM table name

WHERE condition

SUM I syntax
SELECT SUM Column name

FROM table name

WHERE condition
Examples
SELECT COUNT JD

FROM Customers

WHERE JD 2

SELECT AVG Cage

FROM Customers

WHERE country India

select sum Salary

FROM Customers
WHERE country India
SQL ROUND C Function

The Round C function is used to round a

numeric field to the number of decimals


specified

Syntax
SELECT ROUND Column name decimals
FROM table name

Here column name represents the field


to round
decimals represents the number of decimals
to be returned

Example
SELECT Product Name

ROUND Prices O As Rounded price


FROM Products
SQL String manipulation functions
In MySQL there are several manipulation
functions available that allow us to modify
and manipulate string values

SQL LENGTH 7 Function


The LEN Cl function returns the length of
the value in a tent field

Syntax
SELECT LENGTH Column name

FROM table name

Example
SELECT Customer name

LENGTH Address As length of address

FROM customers
SQL LOWER I UPPER I functions
The LOWER C function converts a string
to lowercase
The UPPER I function converts a string
to uppercase

LOWER Syntax
SELECT LOWER Column name

FROM C table name

UPPER Suntan

SELECT UPPER Column name

FROM table name

Example
SELECT UPPER Last Name AS Upper lastname
LOWER First Name As lower first name

FROM customers
SQL SUBSTRING C MIDC l functions

The SUB STRING I function extracts

from a chara
field ters
tent

The MIDC I function also extracts character

from a tent field Here it is not mandatory


to mention length This is MySQL specific
command

SUBSTRING I syntax
SELECT SUBSTRING Column name

start position length As some name

FROM table name

MIDC syntax
SELECT MID Column name

start position length As some name

FROM table name

here length is not mandatory If un

specified if retreives until the end

Example
SELECT SUBSTRING City 1,4 AS Short city
FROM customers

SELECT MID City 1,4 AS Short city


FROM customers

SQL LOCATE C REPLACE I TRIM Cl functions

The LOCATE I function finds a substring


with in a tent field
The REPLACE I function replaces all the

occurances of the search string with the

replace string within the column

The trims I function removes leading and

trailing spaces or other specified characters

from the column

LOCATE C I Syntan
SELECT LOCATE Substring
column name start As some name

FROM table name

start
parameter is optional default is 1

specifies the position to start search from


Example
SELECT LOCATE son full name 5

As position
FROM Customers
start position
y optional
SELECT LOCATE son full name

As position
FROM Customers

REPLACE I syntax
SELECT REPLACE Column name

search replace As some name

FROM table name

Example
SELECT REPLACE description old new

FROM products

UPDATE Products
SET description REPLACE description
old new
TRIM I I syntax
SELECT TRIM Character From column name

As some name

FROM C table name

default character to trim is space if


it is not mentioned

Example
SELECT TRIM FROM product name

As trimmed name

FROM Products

SELECT TRIM Product name


É Eneed to

As trimmed name spaces

FROM products
SQL CONCATC function
The con cat I function is used to
two concate
different ate
tent fields columns in
to one tent field

Syntax
SELECT CON CAT Column I Seperator
columns As some name

FROM table name

Example

SELECT CON CAT Fint Name I


Last Name

As full name

FROM Customers
SQL Dates
The most difficult part when working with

dates is to be sure that the format of the


date we are trying to insert matches the

format of date column in the database

As long as the data contains only the


date portion queries will work as expected
However if time portion is involved it

gets more complicated

SQL Date Datatypes


MySQL comes with the following data types
for storing a date or a date lime value in

the database
1 DATE YY YY MM DD
2 TIME HH MI Ss

3 DATE TIME YY YY MM DD HH MI SS

y TIMESTAMP YY YY MM DD HH MI SS

5 YEAR YYYY or YY
MYSQL NOW CI Function
The now I returns the current date and
time

syntax
NOW C

output
current DATE TIME

YYYY MM DD HH MI SS

CURDATE C Function
The CURDATEC I returns the current date
Syntax
CURDATEC I

output
current date
YYYY MM DD

CURTIME C Function
The Curti MEC t returns the current time

syntax
CURTI MEC I
output
current time
HH MI SS

DATE C function
The DATEC I extracts the date part of

date or date lime expression

can be used with Nowe I CURDATE

functions
Syntax
DATE date

where date is a valid date expression

output date part of expression


YYYY MM DD

YEARC function
The YEAR C I extracts the year part of

date or date lime expression

can be used with Nowe I CORDATE

functions
Syntax
YEAR date

where date is a valid date expression

Output year part of expression


YYYY

MONTH C function
The MONTH C I extracts the month part of

date or date lime expression

can be used with Nowe I CORDATE

functions
Syntax
MONTH date

where date is a valid date expression

Output month part of expression


MM
DAY C function
The DAY C I extracts the day part of

date or date lime expression

can be used with Nowe I CORDATE

functions
Syntax
DAY date

where date is a valid date expression

Output day part of expression

DD

usage
SELECT NOW CI AS Current dateline
CURDATEC AS Current date

CURTO ME CI AS Current Lime

DATE NOW I As extracted date

DAY NOW I As extracted day

MONTH Newel As extracted month

YEAR MWC I AS extracted Year


MYSQL EXTRACT I function
The Extract I l function is used to extract a

specific part such as year month day hour etc

from a date or date lime expression

Syntax
EXTRACT unit FROM date expression

Unit is part to extract YEAR Month DAY


HOUR MINUTE second etc

date expression is the date or date time value

from which to extract the specified part

Example
SELECT EXTRACT YEAR FROM 2023 06 03

As extracted Year

EXTRACT MONTH FROM 2023 06 03

As extracted month

EXTRACT DAY FROM 2023 06 03

As extracted day
we have many supported units in Extracts I
function
MYSQL DATE ADD C I function

The DATE ADD I function is used to add a

specified interval to a date or dateline


It ex ression
allows add years
us to months

days hours minutes seconds etc to a given

date
Syntax
DATE ADD date expression INTERVAL Valve unit

date expression is the date or dateline value


to which the interval should be added

value specifies the number of units to add

unit specifies the unit of time to add

such as YEAR MONTH DAY HOUR MINUTE's


SECOND etc

Example
SELECT DATE ADD 2023 06 03 INTERVAL 1

MONTH As added date


MYSQL DATE SOB I function

The DATE SUB I function is used to subtract a

specified interval to a date or dateline


It ex ression years
allows us to subtract months

days hours minutes seconds etc to a given

date
Syntax
DATE SUB date expression INTERVAL Valve unit

date expression is the date or dateline value


to which the interval should be Substracted

value specifies the number of units to substracted

unit specifies the unit of time to substract


such as YEAR MONTH DAY HOUR MINUTE's
SECOND etc

Example
SELECT DATE SUB 2023 06 03 INTERVAL 1

WEEK AS Substracted date


MYSQL DATE DIFFCI Function
The DATEDIFFI I function is used to calculate

the difference in days between the two dates


It returns the number of days between a given

start date and end date

syntax
DATE DIFF end date start date

end date is the later date or date time value

start date is the earlier date or dateline


Value
Example
SELECT DATE DIFF 2023 06 10 2023 06 03

As date difference
output
output is 7

Cos
SELECT DATED FF end date start date

As date difference
FROM sales
new column is created with difference in

the dates
MYSQL DATE FORMAT function
The DATE FORM ATC I function is used to format
a date or dateline value in to a specific format
It allows us to convert a date or dateline value

to a
formatted string representation
syntax
DATE FORMAT date value format string
date value is the date or dateline value

that we want to format

format string specifies the desired format


for the output

The format string parameter follows a specific


format pattern that includes various placeholders
for different parts of the date or time Below

are some commonly used specifiers


Y year with 4 digits es 2023

i y year with 2 digits es 23

em month with 2 digits eg 06

tod day with 2 digits es 03

YH Hour in 24 hour format as 2 digit es 17 for 5pm


Ii minute as 2 digits es 30
is second as 2 digits es 45

tp AM pm indicator eg AM or pm

Example
SELECT DATE FORMAT 2023 06 03 15 30 45

id tm 44th ti xp As formatted date

output
03 06 2023 3 30PM

er
SELECT DATE FORMAT date Column f Y Y.m Id

As formatted date

FROM sales
MYSQL NULL Functions
There are several functions available to handle
NULL Values Here are some commonly used

NULL functions
IS NULL checks if a valve is NULL

usage
SELECT column name

FROM table name

WHERE Column name IS NULL

Example
SELECT Customer name

FROM Customers

WHERE phone mum IS NULL

IS NOT NULL checks if a Value is not NULL

usage
SELECT column name

FROM table name

WHERE Column name IS NOT NULL

Example
SELECT Product name

FROM products
WHERE ISNT NULL
quantity

COALESCE Returns the first Non Null value

from a list of expressions


usage
SELECT COALESCE expression 1 expression 2

As result

FROM table name

It evaluates the arguments in the order

they are specified and stops at the first


non null Value encountered
Of all the arguments are null it will

return NULL

Example
SELECT employee name COALESCE salary o

As adjusted salary

From employees
This query returns the employee names and
their adjusted salaries If the salary is NULL

it is replaced with o
IF NULL Takes two expressions returns first
expression if not null or returns second one

usage
SELECT IF NULL expression 1 expression 2

As result
FROM table name

It returns expression 1 if it is not Null

otherwise it returns expression 2

If null is used when we want to replace


a single null value with a specified
value

Example
SELECT IF NULL Salary 10000

As adjusted salary

FROM employees
In this example if salary column is
not NULL it will be returned as

adjusted salary If salary is NULL then

function will return 10000 which we have

given as default value as the adjusted


salary
NULLIF Returns NULL if expressions are equal
or returns expression 1

usage
SELECT NULLIF expression 1 expression 2

As result
FROM table name

It returns null if expressions is equal to

expression 2 otherwise returns expression 1


expression 1 expression 2 can be expressions
any
or columns

Example
SELECT NULL IF 5 5 As result

since equal the result will


they are

be NULL

SELECT name NULL IF Salary 5000

As adjusted salary
FROM Employees
there if the original value of salary was 5000

it will be NULL in adjusted salary otherwise


the original salary will reflect
MySQL number functions
MySQL Provides various number functions that

allow us to perform mathematical operations


and manipulate numeric data Here we see

some commonly used number functions

A BSC I function Returns the absolute value of


a number

usage
SELECT ABS C 10

output 10

SELECT ABS quantity As absolute quantity


FROM orders

CE ILL function Returns the smallest integer value

greater than or equal to number

usage
SELECT CEIL 4.2

output 5
SELECT CEIL Salary As rounded salary
FROM employees

FLOOR C function Returns the largest integer


value less than or
equal to number

usage
SELECT FLOOR Y z

output y

er
SELECT FLOOR Salary As rounded Salay
FROM employees

ROUND I function Rounds a number to a

specified number of decimal places

usage
SELECT ROUND Y 567 2

output 4.56

SELECT ROUND Salary 3 As rounded Salay


FROM employees
MOD I function Returns the remainder of a

division operation
usage
SELECT MOD 10,3

output I

SELECT MOD Salary As remainder salary

FROM employees

POWER C I function Raises a number to the power

of another number

usage
SELECT POWER 2,3

output 8

SQ RTC I function Returns the square root of


a number

usage

SELECT SORT IG

Output 4
RAND I function Generates a random number
between o and 1

usage
SELECT RAND C

Output 0.846758567301456

You might also like