Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
14 views

SQL Notes

SQL Notes provides an overview of SQL including what SQL is, what it can do, SQL commands categorized into different languages, what a database and RDBMS are, database schemas, relationships between tables, SQL data types, keys, and more. The document covers the essential concepts around SQL and relational databases at a high level.

Uploaded by

kv.rao1030
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
14 views

SQL Notes

SQL Notes provides an overview of SQL including what SQL is, what it can do, SQL commands categorized into different languages, what a database and RDBMS are, database schemas, relationships between tables, SQL data types, keys, and more. The document covers the essential concepts around SQL and relational databases at a high level.

Uploaded by

kv.rao1030
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 18

SQL Notes

What is SQL?
SQL stands for Structured Query Language

SQL is a query language that communicates with databases.

SQL lets you create, access and manipulate databases

SQL is developed by IBM in 1970s

Although SQL is an ANSI/ISO standard, there are different versions of the SQL
language. Example: MySQL, PostgreSQL, SQLite . . .

However, to be compliant with the ANSI standard, they all support at least the
major commands (such as SELECT , UPDATE , DELETE , INSERT , WHERE ) in a similar
manner.

What Can SQL do?


SQL can execute queries against a database

SQL can retrieve data from a database

SQL can insert records into a database

SQL can update records in a database

SQL can delete records from a database

SQL can create new databases

SQL can create new tables in a database

SQL can set permissions on tables, procedures, and views

These SQL commands are mainly categorized into five categories:

1. DDL – Data Definition Language - Create, Alter, truncate, drop, Rename

2. DQL – Data Query Language - Select

3. DML – Data Manipulation Language - Insert, Update, Delete

SQL Notes 1
4. DCL – Data Control Language - Grant, Revoke

5. TCL – Transaction Control Language - Begin, Commit, Rollback, Save Point

What is a Database?
A database is an organized collection of structured data, usually controlled by a
DBMS( database management system). Databases help us easily store, access, and
manipulate data held on a computer.

SQL is used to build Relational Databases, which are systems that store, update,
retrieve & create data.

SQL Notes 2
Rows - Records, Columns - Fields/ Attributes

RDBMS
RDBMS stands for Relational Database Management System.

Relational DB are made up of tables that are connected to each other with keys.
RDBMS is the basis for SQL, and for all modern database systems such as MS SQL
Server, IBM DB2, Oracle, MySQL, and Microsoft Access.

SQL Notes 3
What is a DB schema or an Entity-Relationship
Diagram?
● A database schema represents how the data is organized and provides information
about the relationships between the tables in a given database.
● In our DB schema, those boxes that you see represent individual tables/relations.
● The lines connecting those tables with each other are called relationships.
● Notice that along with the column/attribute names, a bit of extra detail is also
provided. This is called the data type of a column.

SQL Notes 4
There are multiple types of relationships that two entities (or tables) can share with
each other. Different types of relationships

-● One-to-One Relationship:
○ One row in Table A will be
related to one and only one row in
Table B.
○ Example - marriage between a
husband and his wife. One
husband can have only one wife
and vice versa.

● One-to-Many Relationship:
○ A single row in Table A is related
to multiple rows in Table B.
○ A single row in Table B is related
to a single row in Table A.
○ Example -

SQL Notes 5
■ relationship between a customer and his orders
● A customer can place multiple orders.
● But one order can only be placed by a single customer.

Many-to-Many Relationship:
○ One row in Table A is related to
many rows in Table B.
○ One row in Table B is related to
many rows in Table A.
○ Example - relationship between
customers and suppliers
■ One customer can purchase
from many suppliers.
■ One supplier can sell to many
customers.

SQL Data Types


Each column in a database table is required to have a name and a data type.
An SQL developer must decide what type of data that will be stored inside each
column when creating a table. The data type is a guideline for SQL to understand
what type of data is expected inside of each column.
Note: Data types might have different names in different database. And even if the
name is the same, the size and other details may be different!
There are three main data types that we need to know about:

1. string

2. numeric

3. date and time.

String Data Types

SQL Notes 6
Data Type Description

E.g. for Char(3) data type, a valid data


entry could be IND,
A FIXED length string (can AUS, USA
CHAR(size) contain letters, numbers, and ○ Whereas inputs like INDIA, IN will
special characters). throw an error.
○ Because it’ll require exactly ‘3’
characters.

E.g. for Varchar(5) data type, a valid


entry could be IN, IND,
INDIA
VARCHAR(size) A VARIABLE length string (can
○ Whereas inputs like AMERICA,
contain letters, numbers, and
AUSTRALIA will throw an
special characters).
error.
○ Because it’ll accept only up to ‘5’
characters.

Holds a string with a maximum


TEXT(size)
length of 65,535 bytes

Numeric Data Types

Date and Time Data Types

INT(size) Stores whole numbers, which can be positive or negative.

Stores decimal numbers, or floating point numbers. Floats can hold up to 7


FLOAT(size, d) decimal digits accurately. The number of digits after the decimal point is
specified in the d parameter.

DOUBLE() Doubles can hold up to 15 decimal digits accurately.

A fixed-precision data type that stores exact values. Decimals have higher
DECIMAL() precision than float and double, and are usually used in monetary
applications. However, decimals are slower than float and double

DATE A date. Format: YYYY-MM-DD.

DATETIME(fsp) A date and time combination. Format: YYYY-MM-DD hh:mm:ss.

A timestamp. TIMESTAMP values are stored as the number of seconds


TIMESTAMP(fsp)
since the Unix epoch ('1970-01-01 00:00:00' UTC).

SQL Notes 7
Concept of Keys
Why do we need a key?
Keys in SQL are used
to identify rows in a table uniquely and establish relationships between tables. A
key can be a single column or a group of columns. There are several types of keys in
SQL,

Customers

Question: Which of these columns would you prefer to uniquely identify each record
in the table?

customer_id

Primary Key
● A primary key is a column or a set of columns that uniquely identifies each row in
the table.
● Every table in a database should have a primary key because it ensures the
uniqueness and integrity of the data.
● The primary key's value must be assigned when inserting a record and can never
be updated.
● Note that a relation is allowed to have only one primary key.

SQL Notes 8
Unique Key
A unique key is:
● Unique for all the records of the table.
● Non-updatable, meaning its value cannot be changed once
assigned.
● But may have a NULL value.

Candidate Key
● Any column or set of columns that can act as a primary key is referred to as a
candidate key.
● Every table must have at least a single candidate key (obviously can have multiple
candidate keys) which may have single or multiple attributes.

SQL Notes 9
● Note that candidate keys are just a theoretical concept. They’re not used in real
world applications.

Composite Key
A composite key in SQL is a combination of multiple columns that uniquely identify
each row in a table. A single column can't identify a row uniquely, but a combination
of multiple columns can. For example, a table that stores employee information can
use a composite key that includes the employee's name and date of birth to ensure
that no two employees have the same combination of values.

SQL Notes 10
FOREIGN KEY

A FOREIGN KEY is a field (or collection of fields) in one table, that refers to the PRIMARY

KEY in another table.


The table with the foreign key is called the child table, and the table with the primary
key is called the referenced or parent table.

Primary Key: Uniquely identifies rows, can't be updated. No NULL, No Duplicates


Unique Key: Unique, non-updatable, may have NULL. But No Duplicates.

Foreign Key: Links to the primary key in another table. Can have NULL and Duplicate
Candidate Key: Any column or set of columns that can act as a primary key. Every
table must have at least one candidate key.

SQL Notes 11
What is the difference between a Database vs Data Warehouse?
Data warehouse is a giant database optimized for analytics use cases.

A data warehouse is called an OLAP (Online Analytical Processing) system whereas a


DBMS is called an OLTP (Online Transaction Processing) system.

● Companies choose cloud service providers for data warehousing services.


● There are many cloud service providers like AWS, GCP, Azure, etc.that provide
these data warehousing services.

_______________________________________

The Fundamental Syntax Structure of a SELECT Query

The
SELECTstatement is used to select data from a database.
The SELECT and FROM clauses are generally required because they indicate which
columns to select and from what table.For example,
SELECT CustomerName , City FROM Customers ;

If you want to return all columns, without specifying every column name, you can use
the

SQL Notes 12
SELECT * FROM Customers ;

The SELECT DISTINCT statement is used to return only distinct (different) values.

Concatenating Strings:

CONCAT() :
Thelist of string values you want to merge together are entered into the
CONCAT() function as parameters.

A space can be included by surrounding it with quotes.

Ex. SELECT customer_id,


CONCAT(first_name, " ", last_name) AS full_name
FROM farmers_market.customer
LIMIT 5

UPPER() :
UPPER() is a function that capitalizes string values.
● It’s also possible to nest functions inside other functions, which the SQL interpreter
executes from the “inside” to the “outside.”
● We can enclose the UPPER() function inside the CONCAT() function to uppercase
the full name.

SELECT
customer_id,
CONCAT(UPPER(first_name), " ", last_name) AS full_name
FROM farmers_market.customer
LIMIT 5

Similar to the
UPPER() function, we also have a LOWER() function in case we want to turn
somestring value into lower case

SUBSTR()

SQL Notes 13
The SUBSTRING() function extracts some
Parameter Description
characters from a string.
Required. The
Syntax: SUBSTR( string , start , length ) string string to extrac
from
Ex:
SELECT SUBSTR(CustomerName, 1, 5) AS ExtractString Required. The
start position.
FROM Customers
start The first
position
in string is 1

Required. The
number of
characters to
length
extract. Must
be a positive
number

Filtering data -

The WHERE Clause


The WHERE clause is the part of the SELECT statement in which you list conditions
that are used to determine which rows in the table should be included in the results
set.
● In other words, the WHERE clause is used for filtering of records.

SELECT
product_id, product_name, product_category_id
FROM farmers_market.product
WHERE product_category_id = 1

We can do this using the != or <> (Not equal to) operator

BETWEEN()
The BETWEEN operator selects values within a given range. The values can be
numbers, text, or dates.

The BETWEEN operator is inclusive: begin and end values are included.

SQL Notes 14
Syntax:
SELECT column_name(s) FROM table_name WHERE column_name BETWEEN value1 AND value2;

NOTE:

To display the products outside the range of the previous example, use NOT

BETWEEN :

Between is inclusive of the upper & lower limit of the range specified.

IN()
The IN command allows you to specify multiple values in a WHERE clause.

The IN operator is a shorthand for multiple OR conditions.

Ex:
SELECT * FROM Customers

WHERE Country IN ('Germany', 'France', 'UK');

Please note that the text inside the IN clause are case sensitive.

SELECT
customer_id,
customer_first_name,
customer_last_name
FROM farmers_market.customer
WHERE
LOWER(customer_last_name)IN('diaz' , 'edwards', 'wilson')

OR use
UPPER(customer_last_name)IN('DIAZ' , 'EDWARDS', 'WILSON')

WILDCARDS: %, _
A wildcard character is used to substitute one or more characters in a string.

Wildcard characters are used with the LIKE operator. The LIKE operator is used in
a WHERE clause to search for a specified pattern in a column.

Symbol Description

% Represents zero or more characters

_ Represents a single character

SQL Notes 15
%
The % wildcard represents any number of characters, even zero characters.

Ex: Return all customers that ends with the pattern 'es':
SELECT * FROM CustomersWHERE CustomerName LIKE '%es';

Return all customers that contains the pattern 'mer':


SELECT * FROM CustomersWHERE CustomerName LIKE '%mer%';

The _ wildcard represents a single character. It can be any character or number, but
each _ represents one, and only one, character.

Return all customers with a City starting with any character, followed by "ondon":
SELECT * FROM CustomersWHERE City LIKE '_ondon';

Return all customers with a City starting with "L", followed by any 3 characters,
ending with "on":
SELECT * FROM CustomersWHERE City LIKE 'L___on';

Any wildcard, like % and _ , can be used in combination with other wildcards.
Example

Return all customers that starts with "a" and are at least 3 characters in length:

SQL Notes 16
SELECT * FROM CustomersWHERE CustomerName LIKE 'a__%';

How to sort data in SQL?

This is where the Order By clause comes into play.

● The ORDER BY clause is used to sort the output rows.

● In it, you list the columns by which you want to sort the results, inorder, separated
by commas.

● You can also specify whether you want the sorting to be done inascending (ASC)
or descending (DESC) order.

● The sort order is ascending by default, so the ASC keyword is optional.

Syntax:
SELECT <col1>, <col2>, …

FROM `dataset.table_name`

ORDER BY<col1>, <col2>,<col3>, …

The sorting order is applicable for one single column only.Here the column written
first is given priority so first the data will be sorted on the basis of <col1> then by
<col2> and at the end by <col3>

NOTE:

For strings, ASC sorts text alphabetically and numeric values from low to high, and
DESC sorts them in reverse order.

● In MySQL, NULL values appear first when sorting is done in the ascending order
LIMIT

By using LIMIT, you can get a preview of your current query’s results without having
to wait for all of the results to be compiled.

OFFSET
OFFSET allows you to omit a specified number of rows before the beginning of the
result set.

Order of Execution of a SQL query:

SQL Notes 17
● FROM - The database gets the data from tables in FROM clause.
● SELECT - It determines which columns to include in the final result set.

● ORDER BY - It allows you to sort the result set based on one or morecolumns,
either in ascending or descending order.

● OFFSET - The specified number of rows are skipped from the beginning of the
result set.
● LIMIT - After skipping the rows, the LIMIT clause is applied to restrict the number
of rows returned.

SQL Notes 18

You might also like