SQL Basic to advance Part -2

·

6 min read

Creating a Classroom dataset for practice

CREATE TABLE classroom

(

rollno int8 PRIMARY KEY,

name varchar(50) NOT NULL,

house char(12) NOT NULL,

grade char(1)

);

INSERT INTO classroom

(rollno, name, house, grade)

VALUES

(1, ‘Sam’, ‘Akash’, ‘B’),

(2, ‘Ram’, ‘Agni’, ‘A’),

(3, ‘Shyam’, ‘Jal’, ’B’),

(4, ‘Sundar’, ‘Agni’, ’A’),

(5, ‘Ram’, ‘Yayu’, ‘B’);

SELECT Statement

The SELECT statement is used to select data from a database.

• Syntax

SELECT column_name FROM table_name;

To select all the fields available in the table

• Syntax

SELECT * FROM table_name;

To select distinct/unique fields available in the table

• Syntax

SELECT DISTINCT Column_name FROM table_name;

WHERE Clause

The WHERE clause is used to filter records.

It is used to extract only those records that fulfill a specified condition

• Syntax

SELECT column_name FROM table_name

WHERE conditions;

• Example

SELECT name FROM classroom WHERE grade=‘A’;

Operators In SQL

The SQL reserved words and characters are called operators, which are used with a WHERE clause in a SQL query

Most used operators:

1. Arithmetic operators : arithmetic operations on numeric values

Example: Addition (+), Subtraction (-), Multiplication (*), Division (/), Modulus (%)

2. Comparison operators: compare two different data of SQL table

• Example: Equal (=), Not Equal (!=), Greater Than (>), Greater Than Equals to (>=)

3. Logical operators: perform the Boolean operations

• Example: ALL, IN, BETWEEN, LIKE, AND, OR, NOT, ANY

4. Bitwise operators: perform the bit operations on the Integer values

• Example: Bitwise AND (&), Bitwise OR(|)

LIMIT Clause

The LIMIT clause is used to set an upper limit on the number of tuples returned by SQL.

Example: below code will return 5 rows of data

SELECT column_name FROM table_name

LIMIT 5;

ORDER BY Clause

The ORDER BY is used to sort the result-set in ascending (ASC) or descending order (DESC).

Example: below code will sort the output data by column name in ascending order

SELECT column_name FROM table_name

ORDER BY column_name e ASC;

Functions In SQL

Functions in SQL are the database objects that contains a set of SQL statements to perform a specific task. A function accepts input parameters, perform actions, and then return the result.

Types of Function:

1. System Defined Function : these are built-in functions

• Example: rand(), round(), upper(), lower(), count(), sum(), avg(), max(), etc

2. User-Defined Function : Once you define a function, you can call it in the same way as the built-in functions

Most Used String Functions

String functions are used to perform an operation on input string and return an output string

UPPER() converts the value of a field to uppercase

LOWER() converts the value of a field to lowercase

LENGTH() returns the length of the value in a text field

SUBSTRING() extracts a substring from a string

NOW() returns the current system date and time

• FORMAT() used to set the format of a field

CONCAT() adds two or more strings together

REPLACE() Replaces all occurrences of a substring within a string, with a new substring

TRIM() removes leading and trailing spaces (or other specified characters) from a string

Most Used Aggregate Functions

Aggregate function performs a calculation on multiple values and returns a single value.

And Aggregate functiona are often used with GROUP BY & SELECT statement

• COUNT() returns number of values

• SUM() returns sum of all values

• AVG() returns average value

• MAX() returns maximum value

• MIN() returns minimum value

• ROUND() Rounds a number to a specified number of decimal places

GROUP BY Statement

The GROUP BY statement group rows that have the same values into summary rows. It is often used with aggregate functions (COUNT(), MAX(), MIN(), SUM(), AVG()) to group the result-set by one or more columns

• Syntax

SELECT column_name(s)

FROM table_name

GROUP BY column_name(s);

• Example

SELECT mode, SUM(amount) AS total

FROM payment

GROUP BY mode

HAVING Clause

The HAVING clause is used to apply a filter on the result of GROUP BY based on the specified condition.

The WHERE clause places conditions on the selected columns, whereas the HAVING clause places conditions on groups created by the GROUP BY clause

Syntax

SELECT column_name(s)

FROM table_name

WHERE condition(s)

GROUP BY column_name(s)

HAVING condition(s)

• Example

SELECT mode, COUNT(amount) AS total

FROM payment

GROUP BY mode

HAVING COUNT(amount) >= 3

ORDER BY total DESC

TIMESTAMP

The TIMESTAMP data type is used for values that contain both date and time parts

TIME contains only time, format HH:MI:SS

DATE contains on date, format YYYY-MM-DD

YEAR contains on year, format YYYY or YY

TIMESTAMP contains date and time, format YYYY-MM-DD HH:MI:SS

TIMESTAMPTZ contains date, time and time zone

Below are the TIMESTAMP functions and operators in SQL:

• SHOW TIMEZONE

• SELECT NOW()

• SELECT TIMEOFDAY()

• SELECT CURRENT_TIME

• SELECT CURRENT_DATE

EXTRACT Function

The EXTRACT() function extracts a part from a given date value.

Syntax: SELECT EXTRACT(MONTH FROM date_field) FROM Table

• YEAR

• QUARTER

• MONTH

• WEEK

• DAY

• HOUR

• MINUTE

• DOW – day of week

• DOY – day of year

SUB QUERY

A Subquery or Inner query or a Nested query allows us to create complex query on the output of another query

• Sub query syntax involves two SELECT statements

• Syntax

SELECT column_name(s)

FROM table_name

WHERE column_name operator

( SELECT column_name FROM table_name WHERE ... );

SQL JOIN

•JOIN means to combine something.

• A JOIN clause is used to combine data from two or more tables, based on a related column between them

TYPES OF JOINS

• INNER JOIN

• LEFT JOIN

• RIGHT JOIN

• FULL JOIN

INNER JOIN

• Returns records that have matching values in both tables

• Syntax

SELECT column_name(s)

FROM TableA

INNER JOIN TableB

ON TableA.col_name = TableB.col_name

• Example

SELECT *

FROM customer AS c

INNER JOIN payment AS p

ON c.customer_id = p.customer_id

LEFT JOIN

• Returns all records from the left table, and the matched records from the right table

• Syntax

SELECT column_name(s)

FROM TableA

LEFT JOIN TableB

ON TableA.col_name = TableB.col_name

• Example

SELECT *

FROM customer AS c

LEFT JOIN payment AS p

ON c.customer_id = p.customer_id

RIGHT JOIN

• Returns all records from the right table, and the matched records from the left table

• Syntax

SELECT column_name(s)

FROM TableA

RIGHT JOIN TableB

ON TableA.col_name = TableB.col_name

• Example

SELECT *

FROM customer AS c

RIGHT JOIN payment AS p

ON c.customer_id = p.customer_id

FULL JOIN

• Returns all records when there is a match in either left or right table

• Syntax

SELECT column_name(s)

FROM TableA

FULL OUTER JOIN TableB

ON TableA.col_name = TableB.col_name

• Example

SELECT *

FROM customer AS c

FULL OUTER JOIN payment AS p

ON c.customer_id = p.customer_id

Which JOIN To Use

INNER JOIN: Returns records that have matching values in both tables

LEFT JOIN: Returns all records from the left table, and the matched records from the right table

RIGHT JOIN: Returns all records from the right table, and the matched records from the left table

FULL JOIN: Returns all records when there is a match in either left or right table

That's a wrap........