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

Sample .Introduction To SQL Light

The document provides an overview of SQL concepts including databases, tables, data types, queries, joins, aggregation, sorting, and transactions. It covers topics such as installing and configuring MySQL, creating and modifying database objects, performing CRUD operations, and using functions and triggers.

Uploaded by

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

Sample .Introduction To SQL Light

The document provides an overview of SQL concepts including databases, tables, data types, queries, joins, aggregation, sorting, and transactions. It covers topics such as installing and configuring MySQL, creating and modifying database objects, performing CRUD operations, and using functions and triggers.

Uploaded by

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

Table of Contents

About the book .................................................................................. 8


About the author ........................................................................... 9
Sponsors ...................................................................................... 10
Ebook PDF Generation Tool ......................................................... 12
Book Cover .................................................................................. 13
License ........................................................................................ 14

Databases ........................................................................................ 15
Tables and columns ..................................................................... 16

MySQL ............................................................................................... 18
Installing MySQL .......................................................................... 19
Accessing MySQL via CLI ............................................................. 21
Creating a database .................................................................... 22
Configuring .my.cnf ..................................................................... 23
The mysqladmin command ......................................................... 24
GUI clients ................................................................................... 25

Tables ............................................................................................... 26
Data types ................................................................................... 27
Creating a database .................................................................... 28
Creating tables ............................................................................ 30
Rename tables ............................................................................ 32
Dropping tables ........................................................................... 33
Allowing NULL values .................................................................. 34
Specifying a primary key ............................................................. 35
Index Optimization for Database Queries .................................... 36
Updating tables ........................................................................... 38
Truncate table ............................................................................. 40

Basic Syntax .................................................................................... 41


INSERT ......................................................................................... 43
SELECT ........................................................................................ 44
UPDATE ....................................................................................... 46
DELETE ........................................................................................ 47
Comments ................................................................................... 48
Conclusion ................................................................................... 49

SELECT .............................................................................................. 50
SELECT all columns ..................................................................... 52
Pattern matching ......................................................................... 54
Formatting ................................................................................... 56
SELECT specific columns only ..................................................... 57
SELECT with no FROM Clause ...................................................... 58
SELECT with Arithmetic Operations ............................................. 59
LIMIT ............................................................................................ 60
COUNT ......................................................................................... 61
MIN, MAX, AVG, and SUM ............................................................ 62
DISTINCT ..................................................................................... 64
Conclusion ................................................................................... 66

WHERE .............................................................................................. 67
WHERE Clause example .............................................................. 68
Operators .................................................................................... 70
AND keyword ............................................................................... 71
OR keyword ................................................................................. 72
LIKE operator ............................................................................... 73

IN operator ...................................................................................... 74
IS operator ................................................................................... 75
BETWEEN operator ...................................................................... 76
Conclusion ................................................................................... 77

Sorting with ORDER and GROUP BY ............................................ 78


ORDER BY .................................................................................... 79
GROUP BY .................................................................................... 82
HAVING Clause ............................................................................ 83

INSERT .............................................................................................. 84
Inserting multiple records ........................................................... 86
Inserting multiple records using another table ............................ 87

UPDATE ............................................................................................ 88
Updating records using another table ......................................... 91

DELETE ............................................................................................. 92
Delete from another table ........................................................... 94

JOIN ................................................................................................... 95
CROSS JOIN .................................................................................. 98
INNER JOIN ................................................................................. 100
LEFT JOIN ................................................................................... 103
RIGHT JOIN ................................................................................. 104
The Impact of Conditions in JOIN vs. WHERE Clauses ................ 106
Equivalence of RIGHT and LEFT JOINs ....................................... 108
Conclusion ................................................................................. 109
SQL | DDL, DQL, DML, DCL and TCL Commands ...................... 110

SQL Sub Queries ........................................................................... 115

SQL - UNIONS CLAUSE ................................................................. 119

Relational Keys- Keys in a Relational Database ...................... 123


Types of Relational Keys ........................................................... 124

Logical Operator Keywords ........................................................ 127

HAVING Clause .............................................................................. 128


Syntax ....................................................................................... 129
Description ................................................................................ 130
Aggregate Functions ................................................................. 131
Aggregate Functions Examples ................................................. 132
Having clause Examples ............................................................ 135

Essential MySQL Functions ......................................................... 137


Numeric Functions ..................................................................... 138
STRING Functions ...................................................................... 140
DATE Functions ......................................................................... 142
Formatting Dates and Times ..................................................... 144
Calculating Dates and Times ..................................................... 145

Triggers In SQL ............................................................................. 146

Example : ....................................................................................... 148


Transaction Control Language ................................................... 151
TCL Commands ......................................................................... 152
COMMIT ..................................................................................... 153
ROLLBACK ................................................................................. 154
SAVEPOINT ................................................................................ 155
Examples ................................................................................... 156
Conclusion ................................................................................. 160

Data Control Language ................................................................ 161


DCL Commands ......................................................................... 162
GRANT ....................................................................................... 163
REVOKE ..................................................................................... 164
Conclusion ................................................................................. 168

The MySQL dump command ....................................................... 169


Exporting a Database ................................................................ 170
Exporting all databases ............................................................. 171

Automated backups ..................................................................... 173


Conclusion ................................................................................. 175

Learn Materialize by running streaming SQL on your nginx logs


......................................................................................................... 176

Prerequisites ................................................................................. 177

What is Materialize ...................................................................... 178

Installing Materialize ................................................................... 179


Installing mzcli .............................................................................. 180
Installing nginx .......................................................................... 181
Adding a Materialize Source ...................................................... 182

Creating a Materialized View ..................................................... 184

Reading from the view ................................................................ 186

Conclusion ..................................................................................... 189

Conclusion ..................................................................................... 190


Other eBooks ............................................................................. 191
About the book

This version was published on October 13,2021

This open-source introduction to SQL guide will help you learn the
basics of SQL and start using relational databases for your SysOps,
DevOps, and Dev projects. Whether you are a DevOps/SysOps engineer,
developer, or just a Linux enthusiast, you will most likely have to use
SQL at some point in your career.

The guide is suitable for anyone working as a developer, system


administrator, or DevOps engineer who wants to learn the basics of
SQL.

8
About the author

My name is Bobby Iliev, and I have been working as a Linux DevOps


Engineer since 2014. I am an avid Linux lover and supporter of the
open-source movement philosophy. I am always doing that which I
cannot do in order that I may learn how to do it, and I believe in sharing
knowledge.

I think it's essential always to keep professional and surround yourself


with good people, work hard, and be nice to everyone. You have to
perform at a consistently higher level than others. That's the mark of a
true professional.

For more information, please visit my blog at https://bobbyiliev.com,


follow me on Twitter @bobbyiliev_ and YouTube.

9
Sponsors

This book is made possible thanks to these fantastic companies!

Materialize

The Streaming Database for Real-time Analytics.

Materialize is a reactive database that delivers incremental view


updates. Materialize helps developers easily build with streaming data
using standard SQL.

DigitalOcean

DigitalOcean is a cloud services platform delivering the simplicity


developers love and businesses trust to run production applications at
scale.

It provides highly available, secure, and scalable compute, storage, and


networking solutions that help developers build great software faster.

Founded in 2012 with offices in New York and Cambridge, MA,


DigitalOcean offers transparent and affordable pricing, an elegant user
interface, and one of the largest libraries of open source resources
available.

For more information, please visit https://www.digitalocean.com or


follow @digitalocean on Twitter.

If you are new to DigitalOcean, you can get a free $100 credit and spin
up your own servers via this referral link here:

Free $100 Credit For DigitalOcean

10
DevDojo

The DevDojo is a resource to learn all things web development and web
design. Learn on your lunch break or wake up and enjoy a cup of coffee
with us to learn something new.

Join this developer community, and we can all learn together, build
together, and grow together.

Join DevDojo

For more information, please visit https://www.devdojo.com or follow


@thedevdojo on Twitter.

11
Ebook PDF Generation Tool

This ebook was generated by Ibis developed by Mohamed Said.

Ibis is a PHP tool that helps you write eBooks in markdown.

12
Book Cover

The cover for this ebook was created with Canva.com.

If you ever need to create a graphic, poster, invitation, logo,


presentation – or anything that looks good — give Canva a go.

13
License

MIT License

Copyright (c) 2020 Bobby Iliev

Permission is hereby granted, free of charge, to any person obtaining a


copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to permit
persons to whom the Software is furnished to do so, subject to the
following conditions:

The above copyright notice and this permission notice shall be included
in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY


KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS
OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR
OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

14
Databases

Before we dive deep into SQL, let's quickly define what a database is.

The definition of databases from Wikipedia is:

A database is an organized collection of data, generally stored and


accessed electronically from a computer system.

In other words, a database is a collection of data stored and structured


in different database tables.

15
Tables and columns

You've most likely worked with spreadsheet systems like Excel or


Google Sheets. At the very basic, database tables are quite similar to
spreadsheets.

Each table has different columns which could contain different types of
data.

For example, if you have a todo list app, you would have a database,
and in your database, you would have different tables storing different
information like:

Users - In the users table, you would have some data for your
users like: username, name, and active, for example.
Tasks - The tasks table would store all of the tasks that you are
planning to do. The columns of the tasks table would be for
example, task_name, status, due_date and priority.

The Users table will look like this:

+----+----------+---------------+--------+
| id | username | name | active |
+----+----------+---------------+--------+
| 1 | bobby | Bobby Iliev | true |
| 2 | grisi | Greisi I. | true |
| 3 | devdojo | Dev Dojo | false |
+----+----------+---------------+--------+

Rundown of the table structure:

We have 4 columns: id, username, name and active.


We also have 3 entries/users.
The id column is a unique identifier of each user and is auto-
incremented.

16
In the next chapter, we will learn how to install MySQL and create our
first database.

17
MySQL

Now that you know what a database, table, and column are, the next
thing that you would need to do is install a database service where you
would be running your SQL queries on.

We will be using MySQL as it is free, open-source, and very widely used.

18
Installing MySQL

Depending on your operating system, to install MySQL run the following


commands.

Install MySQL on Ubuntu

To install MySQL on a Linux or Ubuntu machine, run the following


commands:

First update your apt repository:

sudo apt update -y

Then install MySQL:

sudo apt install mysql-server mysql-client

We are installing two packages, one is the actual MySQL server, and the
other is the MySQL client, which would allow us to connect to the
MySQL server and run our queries.

To check if MySQL is running, run the following command:

sudo systemctl status mysql.service

To secure your MySQL server, you could run the following command:

sudo mysql_secure_installation

19
Then follow the prompt and choose a secure password and save it in a
secure place like a password manager.

With that, you would have MySQL installed on your Ubuntu server. The
above should also work just fine on Debian.

Install MySQL on Mac

I would recommend installing MySQL using Homebrew:

brew install mysql

After that, start MySQL:

brew services start mysql

And finally, secure it:

mysql_secure_installation

In case that you ever need to stop the MySQL service, you could do so
with the following command:

brew services stop mysql

Install MySQL on Windows

To install MySQL on Windows, I would recommend following the steps


from the official documentation here:

https://dev.mysql.com/doc/refman/8.0/en/windows-installation.html

20
Accessing MySQL via CLI

To access MySQL run the mysql command followed by your user:

mysql -u root -p

21
Creating a database

After that, switch to the demo database that we created in the previous
chapter:

USE demo;

To exit the just type the following:

exit;

22
Configuring .my.cnf

By configuring the ~/.my.cnf file in your user's home directory, MySQL


would allow you to log in without prompting you for a password.

To make that change, what you need to do is first create a .my.cnf file
in your user's home directory:

touch ~/.my.cnf

After that, set secure permissions so that other regular users could not
read the file:

chmod 600 ~/.my.cnf

Then using your favourite text editor, open the file:

nano ~/.my.cnf

And add the following configuration:

[client]
user=YOUR_MYSQL_USERNAME
password=YOUR_MYSQL_PASSWORD

Make sure to update your MySQL credentials accordingly, then save the
file and exit.

After that, if you run just mysql, you will be authenticated directly with
the credentials that you've specified in the ~/.my.cnf file without being
prompted for a password.

23
The mysqladmin command

As a quick test, you could check all of your open SQL connections by
running the following command:

mysqladmin proc

The mysqladmin tool would also use the client details from the
~/.my.cnf file, and it would list your current MySQL process list.

Another cool thing that you could try doing is combining this with the
watch command and kind of monitor your MySQL connections in almost
real-time:

watch -n1 mysqladmin proc

To stop the watch command, just hit CTRL+C

24
GUI clients

If you prefer using GUI clients, you could take a look a the following
ones and install them locally on your laptop:

MySQL Workbench
Sequel Pro
TablePlus

This will allow you to connect to your database via a graphical interface
rather than the mysql command-line tool.

If you want to have a production-ready MySQL database, I would


recommend giving DigitalOcean a try:

Worry-free managed database hosting

25
Tables

Before we get started with SQL, let's learn how to create tables and
columns.

As an example, we are going to create a users table with the following


columns:

id - this is going to be the primary key of the table and would be


the unique identifier of each user.
username - this column would hold the username of our users.
name - here, we will store the full name of users.
status - here, we will store the status of a user, which would
indicate if a user is active or not.

You need to specify the data type of each column.

In our case it would be like this:

id - Integer
username - Varchar
name - Varchar
status - Number

26
Data types

The most common data types that you would come across are:

CHAR(size): Fixed-length character string with a maximum length of


255 bytes.
VARCHAR(size): Variable-length character string. Max size is
specified in parenthesis.
TEXT(size): A string with a maximum length of 65,535 bytes.
INTEGER(size) or INT(size): A medium integer.
BOOLEAN or BOOL: Holds a true or false value.
DATE: Holds a date.

Let's have the following users table as an example:

id: We would want to set the ID to INT.


name: The name should fit in a VARCHAR column.
about: As the about section could be longer, we could set the
column data type to TEXT.
birthday: For the birthday column of the user, we could use DATE.

For more information on all data types available, make sure to check
out the official documentation here.

27
Creating a database

As we briefly covered in the previous chapter, before you could create


tables, you would need to create a database by running the following:

First access MySQL:

mysql -u root -p

Then create a database called demo_db:

CREATE DATABASE demo_db;

Note: the database name needs to be unique, if you already have a


database named demo_db you would receive an error that the database
already exists.

You can consider this database as the container where we would create
all of the tables in.

Once you've created the database, you need to switch to that database:

USE demo_db;

You can think of this as accessing a directory in Linux with the cd


command. With USE, we switch to a specific database.

Alternatively, if you do not want to 'switch' to the specific database, you


would need to specify the so-called fully qualified table name. For
example, if you had a users table in the demo_db, and you wanted to
select all of the entries from that table, you could use one of the

28
following two approaches:

Switch to the demo_db first and then run a select statement:

USE demo_db;
SELECT username FROM users;

Alternatively, rather than using the USE command first, specify the
database name followed by the table name separated with a dot:
db_name.table_name:

SELECT username FROM demo_db.users;

We are going to cover the SELECT statement more in-depth in the


following chapters.

29
Creating tables

In order to create a table, you need to use the CREATE TABLE statement
followed by the columns that you want to have in that table and their
data type.

Let's say that we wanted to create a users table with the following
columns:

id: An integer value


username: A varchar value
about: A text type
birthday: Date
active: True or false

The query that we would need to run to create that table would be:

CREATE TABLE users


(
id INT,
username VARCHAR(255),
about TEXT,
birthday DATE,
active BOOL
);

Note: You need to select a database first with the USE command as
mentioned above. Otherwise you will get the following error: `ERROR
1046 (3D000): No database selected.

To list the available tables, you could run the following command:

SHOW TABLES;

30
This is a sample from "Introduction to SQL" by Bobby Iliev.

For more information, Click here.

You might also like