29
-SQL- SQL Ebook By H. H May8 2016 Mobile friendly eBook NO: 001

Sql tiny ebook by H.H

Embed Size (px)

Citation preview

Page 1: Sql tiny ebook by H.H

-SQL-

SQL

Ebook By H. H

May82016

Mobile friendly eBook

NO: 001

Page 2: Sql tiny ebook by H.H

Welcome to the series of tiny, mobile friendly eBooks.

“This eBook is designed to be read on device with small display. Specifically smartphones, also with phablets and tablets though you can, however, read on any device with ability to view document in PDF format”.

Yeye's Ebooks.

© 2016 DSM, Tanzania.

◄This issue may be updated►

Page 3: Sql tiny ebook by H.H

ABOUT THIS...

This is eBook for learning SQL more simply. In order to practise any SQL query, you have to install programs which are SQL-compatible. You can try with native MS Access or OpenOffice DB to run. However you may sometimes encounter errors because not all commands are applicable to all Database software.

This eBook does not explain deeply about query and not all queries are discussed so you still need other helps.

Thanks

Hamimu

Yeye!

May 8, 2016

Page 4: Sql tiny ebook by H.H

SHORTCUTS:

Click the keyword below to directly go to the page where it is available.

database ■ create ■ insert ■ select ■ now■ drop ■ where ■ update ■ alter ■ order ■ like ■ and ■ or ■ null ■ between ■ avg ■ sum ■ ucase ■ lcase ■ min ■ max ■ first ■ last ■ round ■ hour ■ mid ■ count ■ primary ■ top ■ limit ■ len ■ show ■ use.

You can also use table of contents.

>>Go to the last page...

Page 5: Sql tiny ebook by H.H

CONTENTS:No Title Page

1 Introduction 01

2 Data Types 02

3 Database and Table 04

4 Primary Key 06

5 Operators 08

6 Select (Query) 10

7 Functions 15

8 Case switch and More 19

9 Range and Update 21

Page 6: Sql tiny ebook by H.H

SQLThe Structured Query Language.

Page 7: Sql tiny ebook by H.H

01. Introduction:

SQL or Structured Query Language is used to manipulate data from Database.◘ SQL is very easy to use however you must follow its syntax.◘ SQL is case-insensitive.◘ SQL is being used since 1970s.◘ Informix, MS Access, Oracle, Sybase, SQL Server, MySQL and more are all based on SQL.◘ SQL was called SEQUEL but this name is not now related to SQL. So they should not be used interchangeably. ◘ SQL is specifically for RDBMS, relational database management system.◘ All SQL statements end with semicolon (;)

In this book, all SQL commands or reserved words are written in red colour.

SQL H.001 01

Page 8: Sql tiny ebook by H.H

02. Data types:

Data type determines what kind of information is accessed or manipulated. In pure SQL there are many data types. Here we will list only few important of them.

a) For Numbers:◘ float, real, int, numeric, bigint, decimal, bit, binary, varbinary.◘ Note that, the data type float is used when you want to include number with decimal point. So if you are not sure what kind of number you want to use, we recommend you use float or real.

b) For Text:◘ char, varchar, text, nchar, ntext, nvarchar.◘ In normal or practical use, we recommend varchar and text to be used.

c) Date and Time:◘ date, datetime, time, smalldatetime.

SQL H.001 02

Page 9: Sql tiny ebook by H.H

◘ Date stores full date like Feb 8, 2016.◘ Time format is like, 7:25 A.M.◘ Datetime has the date range from Jan 1, 1753 to Dec 9, 9999.◘ Smalldatetime range starts from Jan 1, 1900 to Jun 6, 2079.

d) Other Data Types:Other data types are sql_variant, xml, table, cursor, uniqueidentifier, money, timestamp and more.

SQL H.001 03

Page 10: Sql tiny ebook by H.H

03. Database and Table:

a) Creating Database:Database is what tables are created on.Here we create database known as HomeData:create database HomeData;To delete database replace command create with drop...drop database HomeData;To list databases use show databases; command. To select database use 'use' command... use HomeData;

b) Creating Table:Suppose the table is called Orodha with columns ID, Name, Game and Score , we can create it as follows..create table Orodha(ID int, Name text(50), Game varchar, Score float);

SQL H.001 04

ID Name Game Score

Page 11: Sql tiny ebook by H.H

◘ Numbers inside brackets after data type indicate limitation you give, for example, text characters should not exceed 50.As you have seen, the table is created but it has no data. To make it have data, we use INSERT INTO command. See example:insert into Orodha(ID, Name, Game, Score) values(1, 'Juma', 'FG', 65);The table produced will be:

This table has no primary key, you will learn more later about primary key.◘ Strings are always enclosed with (single) quotation marks as 'FG'.

c) Deleting table:To delete table we also use DROP command with TABLE reserved word.drop table Orodha;

SQL H.001 05

ID Name Game Score

1 Juma FG 65

Page 12: Sql tiny ebook by H.H

04. Primary key:

a) Explanation: Primary key is used to identify records or rows from the table.◘ Primary key should not have the NULL values.◘ Primary key contains unique values.◘ Primary key is only one per table.◘ Primary key consists of one or multiple fields. If primary key is formed by multiple fields, it is now called composite key.◘ Because primary key needs unique values, ID column is usually dedicated to be primary key though not always necessary.

b) Foreign key: (See page 22).This is referencing key used to link two tables. The link is between it and primary key.◘ Foreign key can also be formed with combinations of columns.◘ Values of foreign key matches the values of primary key. Both primary key and foreign key are SOL-reserved words.

SQL H.001 06

Page 13: Sql tiny ebook by H.H

c) Creating primary key:Let's create again Orodha table but now with ID as primary key. create table Orodha(ID int, Name text(50), Game varchar, Score float, primary key(ID));However if table already exists, you can simply create primary key as....alter table Orodha add primary key(ID);◘ More than one column in primary key are mentioned as ...primary key(ID, Name); when creating table.

d) Deleting primary key:Again, alter table command is used but now you replace add keyword with word drop.alter table Orodha drop primary key(ID);If primary key has many columns, you have to mention all.

SQL H.001 07

ID Name Game Score

Page 14: Sql tiny ebook by H.H

05. Operators:

SQL consists of many operators. These are also used in other programming languages. There are:+ used for addition.- for subtraction.* for multiplication./ for division and% for modulus.

Apart from those arithmetical, there are operators for comparison. These are:= equal sign.!= or <> not equal.> greater than.< less than.>= greater or equal.<= less or equal. !< not less than.!> not greater than.◘ There are many logical operators as well which are ALL, AND, ANY, BETWEEN, EXISTS, IN, LIKE, NOT, OR, IS NULL and UNIQUE

SQL H.001 08

Page 15: Sql tiny ebook by H.H

You will learn more about those operators as you browse this eBook.

What is NULL value?Null value is used to present that the certain field has no value, or it is blank, however the white space is not null value replacement. When you assign the field to be not null, the field is not null even though it's blank visually.

NOT NULL is assigned during table creation.create table Orodha(ID int, Name text(50), Game varchar not null, Score float, primary key(ID)); NOT NULL is written after data type as you have seen example above in the Game column.

SQL H.001 09

Page 16: Sql tiny ebook by H.H

06. SELECT Query:

SELECT command is used to search data from database table. Table should first be present to use this query. This query is used with reserved word FROM in order to obtain data.

select Name, Score from Orodha;If you run that query, the columns Name and Score will be displayed with all associated data. Also you can use wildcard * to select all.select * from Orodha; This means that, columns will be displayed or in other word entire table will be displayed. The asterisk symbol means ALL.

SQL H.001 10

ID Name Game Score

1 Juma FG 65

2 Salu Damma 74

Page 17: Sql tiny ebook by H.H

a) WHERE Clause.In SELECT query, there is where clause that adds more criteria to the command. It is used to implement certain condition. Other queries that can be used with where are INSERT, UPDATE and DELETE with the help of operators.

select Score from Orodha where Score<70;

Alsoselect * from Orodha where Score<70;

Entire row with 65 score will be displayed.

SQL H.001 11

ID Name Game Score

1 Juma FG 65

2 Salu Damma 74

Score

65

The output will be:

Page 18: Sql tiny ebook by H.H

This row will be displayed.

You can use any appropriate operator, for example... select * from Orodha where Name='Salu';

This is the output:

◘ Do not forget to enclose string-based data with quotation marks in any SQL query.

b) WHERE with AND/OR:AND is used to combine criteria in SQL statement. You can use AND more than once.

SQL H.001 12

ID Name Game Score

1 Juma FG 65

ID Name Game Score

2 Salu Damma 74

Page 19: Sql tiny ebook by H.H

select * from Orodha where Name='Salu' and Score<72;The table will be displayed...

With OR, the condition which is true will be applicable, you can also use OR more than once.select ID, Name, Game, Score from Orodha where Game='FG' or Score>90;

c) WHERE with LIKE:We use keyword like to fetch data with certain comparison. We may not write full field name instead we can use two wildcards to find data. The wildcard % is used to replace one or more characters whereas underscore _ replaces single characters.

SQL H.001 13

ID Name Game Score

1 Juma FG 65

2 Salu Damma 74

Page 20: Sql tiny ebook by H.H

select * from Orodha where Name like '%lu';

This means select data from Orodha table where field in the Name column ends with “lu”. Therefore the name Salu will be displayed in Name column. It is also appropriate to use logical operators. select * from Orodha where Name like '%lu' and 'Jum_';

d) ORDER BY Clause:This is used for sorting data for example ascending (asc) and descending (desc). By default, data are sorted in ascending order. These orders could be numerically or alphabetically depending upon data types.select * from Orodha order by ID, Name desc;

The output will be...

SQL H.001 14

ID Name

2 Salu

1 Juma

Page 21: Sql tiny ebook by H.H

07. Functions:

There are functions which are used to manipulate data in SQL. These are avg(), count(), first(), last(), max(), min() and sum().

a) Average and Count:If we want to calculate average of data we use avg() function. Similarly if we want to count number of data we use count() function. The SELECT query is used in function.

You simply mention column(s) in the function brackets....select avg(Score) from Orodha;The result will be 69.5

SQL H.001 15

ID Name Game Score

1 Juma FG 65

2 Salu Damma 74

Page 22: Sql tiny ebook by H.H

The following is COUNT() function which will count all records because the willdcard for ALL is used and there is no condition specified.select count(*) from Orodha;With condition is like:select count(*) from Orodha where name='Juma','Salu';

b) First and Last:In Microsoft Access the first function is used to output first value while the alternative “TOP 1” keyword can be used in SQL Server.select first(Game) from Orodha; As you have seen, you put the column name in the bracket.select top 1 Game from Orodha order by ID asc;You can use this way for other Databases.select Game from Orodha order by ID asc limit 1; You can use your own trick to achieve this example by using other SQL conditions. Example you can use > or <.

The function LAST() is also used only on

SQL H.001 16

Page 23: Sql tiny ebook by H.H

Microsoft Access with the same syntax like FIRST() function.select last(Game) from Orodha;In SQL server, the TOP keyword is used with DESC keyword for now...select top 1 Game from Orodha order by ID desc;Other:select Game from Orodha order by ID desc limit 1;

c) Maximum, Minimum and Sum:The function MAX() and MIN() are used to output the possible highest and lowest values respectively. The function SUM() calculates total.

select max(Score) from Orodha;The result will be 74.

SQL H.001 17

ID Name Game Score

1 Juma FG 65

2 Salu Damma 74

Page 24: Sql tiny ebook by H.H

select min(Score) from Orodha;The result will be 65.select sum(Score) from Orodha;The result will be 139.

SQL H.001 18

Page 25: Sql tiny ebook by H.H

08. Case Switch and More:

SQL allows to change text from UPPERCASE to lowercase. To achieve this we use special functions, UCASE() and LCASE(). In SQL Server we write UPPER() and LOWER() to replace them.

Examples: a) Lowercase to uppercase:select ucase(Name) from Orodha;b) Lowercase to uppercase:select lcase(Name) from Orodha;

For SQL server:a) Lowercase to uppercase:select upper(Name) from Orodha;b) Lowercase to uppercase:select lower(Name) from Orodha;

SQL can deal more with character, the function known as MID() can extract character from field.

SQL H.001 19

Page 26: Sql tiny ebook by H.H

Example:select mid(Name,1,3) as TinyWord from Orodha; This statement means select the first three letters from Name column and call it as TinyWord from that table.To know value length of text field, we use the function LEN(), see example...select len(Name) from Orodha;In SQL we can round off number to the decimal places with ROUND() function.Example:select round(Score,2) from Orodha;means round off score points to two decimal places. It depends upon which Database tool we use, the way this function can be handled.

The function NOW() is used to show current date and time: select now(); or for time only you can write select hour(); simply.

SQL H.001 20

Page 27: Sql tiny ebook by H.H

9. Range and Update:

The BETWEEN clause is used to select range of numbers.

Example:select * from Orodha where Score between 74 and 92; Also you can select their complements by adding NOT operator...select * from Orodha where Score not between 74 and 92;So, all values between that range will be excluded in the output.…......................................

SQL H.001 21

ID Name Game Score

1 Juma FG 65

2 Salu Damma 74

3 Asha Jigsaw 74.5

4 Sudi Bounce 80

5 Hussein PnP 92

Page 28: Sql tiny ebook by H.H

We can update existing records on the database table.

Suppose we want to rename the game Damma as 'Njiambili' without destroying table, this can be done as follows...update Orodha set Game = 'Njiambili' where ID = 2;…......................................Up to now, you have manipulated enough your table, so you can create child table to link with parent table using foreign key as you have learned on page 6, you can do as follows:create table Idadi(ID int not null, Player text(25), Rank varchar, Points int foreign key(ID) references Orodha(ID));◘ Or for some database tools the foreign key line is written as:….foreign key references Orodha(ID));

SQL H.001 22

ID Name Game Score

1 Juma FG 65

2 Salu Damma 74

Page 29: Sql tiny ebook by H.H

THANK YOU

I hope you enjoyed it.

Visit website SQL-Course to learn more about SQL:http://www.sqlcourse.com

BACK:Go to cover.Go to shortcuts.Go to table of contens.Go to the first page.

SQL H.001 23