mysql

Synopsis

To get introduced to SQL, we first need to know about Databases and Database Management Systems(DBMS). Data is basically a collection of facts related to some object. A Database is a collection of small units of data arranged in a systematic manner. A Relational Database Management System is a collection of tools that allows the users to manipulate, organize and visualize the contents of a database while following some standard rules that facilitate fast response between the database and the user side.

After getting introduced to the concept of data, databases and DBMS/RDBMS, we can finally learn about SQL. SQL or Structured Query Language is basically the language that we (the user) use to communicate with the Databases and get our required interpretation of data out of it. It is used for storing, manipulating and retrieving data out of a database.

SQL Features

The following functionalities can be performed on a database using SQL:

Basic SQL

Create Database and drop database

COMMANDSYNTAXDESCRIPTION
CREATE DATABASECREATE DATABASE database-nameUsed to create new SQL database in the server
DROP DATABASECREATE DATABASE database-nameUsed to drop the existing database

String Datatype

The table below lists all the String datatype available in SQL, along with their descriptions:

DatatypeDescription
CHAR(size)A fixed-length string containing numbers, letters or special characters. Length may vary from 0-255.
VARCHAR(size)Variable-length string where the length may vary from 0-65535. Similar to CHAR.
TEXT(size)Can contain a string of size up to 65536 bytes.
TINY TEXTCan contain a string of up to 255 characters.
MEDIUM TEXTCan contain a string of up to 16777215 characters.
LONG TEXTCan contain a string of up to 4294967295 characters.
BINARY(size)Similar to CHAR() but stores binary byte strings.
VARBINARY(size)Similar to VARCHAR() but stores binary byte strings.
BLOB(size)Holds blobs up to 65536 bytes.
TINYBLOBIt is used for Binary Large Objects and has a maximum size of 255bytes.
MEDIUMBLOBHolds blobs up to 16777215 bytes.
LONGBLOBHolds blobs upto 4294967295 bytes.
ENUM(val1,val2)String object that can have only 1 possible value from a list of size at most 65536 values in an ENUM list. If no value is inserted, a blank value is inserted.
SET(val1,val2,…)String object with 0 or more values, chosen from a list of possible values with a maximum limit of 64 values.

Numeric Datatype:

The table below lists all the Numeric Datatype in SQL along with their descriptions:

DatatypeDescription
BIT(size)Bit-value type, where size varies from 1 to 64. Default value: 1
INT(size)Integer with values in the signed range of -2147483648 to 2147483647 and values in the unsigned range of 0 to 4294967295.
TINYINT(size)Integer with values in the signed range of -128 to 127 and values in the unsigned range of 0 to 255.
SMALLINT(size)Integer with values in the signed range of -32768 to 32767 and values in the unsigned range of 0 to 65535.
MEDIUMINT(size)Integer with values in the signed range of -8388608 to 8388607 and values in the unsigned range of 0 to 16777215.
BIGINT(size)Integer with values in the signed range of 9223372036854775808 to 9223372036854775807 and values in the unsigned range of 0 to 18446744073709551615.
BOOLEANBoolean values where 0 is considered as FALSE and non-zero values are considered TRUE.
FLOAT (p)The floating-point number is stored. If the precision parameter is set between 0 to 24, the type is FLOAT() else if it lies between 25 to 53, the datatype is DOUBLE().
DECIMAL(size,d)Decimal number with a number of digits before decimal place set by size parameter, and a number of digits after the decimal point set by d parameter. Default values: size = 10, d = 10. Maximum Values: size = 65, d = 30.

Date/Time Datatype:

The datatype available in SQL to handle Date/Time operations effectively are called the Date/Time datatype.
The table listed below all the Date/Time variables in SQL along with their description:

DatatypeDescription
DATEStores date in YYYY-MM-DD format with dates in the range of ‘1000-01-01’ to ‘9999-12-31’.
TIME(fsp)Stores time in hh:mm:ss format with times in the range of ‘-838:59:59’ to ‘838:59:59’.
DATETIME(fsp)Stores a combination of date and time in YYYY-MM-DD and hh:mm:ss format, with values in the range of ‘1000-01-01 00:00:00’ to ‘9999-12-31 23:59:59’.
TIMESTAMP(fsp)It stores values relative to the Unix Epoch, basically a Unix Timestamp. Values lie in the range of ‘1970-01-01 00:00:01’ UTC to ‘2038-01-09 03:14:07’ UTC.
YEARStores values of years as a 4digit number format, with a range lying between -1901 to 2155.

Tables

COMMANDSYNTAXDESCRIPTION
CREATE TABLECREATE TABLE table_name (column1 datatype,column2 datatype,column3 datatype)Used to create new table
DROP DATABASECREATE DATABASE database-nameUsed to drop the existing database
TRUNCATE TABLETRUNCATE TABLE table_nameused to delete the data inside a table, but not the table itself.

Alter Table

COMMANDSYNTAXDESCRIPTION
ALTER TABLE ADDALTER TABLE table_name ADD column_name datatypeUsed to add column in existing table
ALTER TABLE DROPALTER TABLE table_name DROP COLUMN column_nameUsed to drop column in existing table
ALTER TABLE MODIFYALTER TABLE table_name MODIFY COLUMN column_name datatypeUsed to modify column in existing table

Insert Table

COMMANDSYNTAXDESCRIPTION
INSERT INTOINSERT INTO table_name (column1, column2, column3, …) VALUES (value1, value2, value3, …);Used to insert data for particular columnn to add new records into existing table
INSERT INTOINSERT INTO table_name VALUES (value1, value2, value3, …);used to insert new record in existing table with all column

Update Table

COMMANDSYNTAXDESCRIPTION
UPDATEUPDATE table_name SET column1 = value1, column2 = value2, … WHERE condition;Used to update data for particular row for existing records in existing table
UPDATEUPDATE table_name SET column1 = value1, column2 = value2, … ;Used to update data for all row exist in existing table

Delete Table

COMMANDSYNTAXDESCRIPTION
DELETEDELETE FROM table_name WHERE condition;Used to delete data for particular row for existing records in existing table
DELETEDELETE FROM table_name;Used to delete data for all row exist in existing table

Important Sql Keywords

KeywordDescriptionExample
ADDWill add a new column to an existing table.ALTER TABLE student ADD email_address VARCHAR(255)
ALTER TABLEAdds edits or deletes columns in a tableALTER TABLE student DROP COLUMN email_address
ALTER COLUMNCan change the datatype of a table’s columnALTER TABLE student ALTER COLUMN phone VARCHAR(15)
ASRenames a table/column with an alias existing only for the query duration.SELECT name AS student_name, phone FROM student
ASCUsed in conjunction with ORDER BY to sort data in ascending order.SELECT column1, column2, … FROM table_name ORDER BY column1, column2, … ASC
DESCUsed in conjunction with ORDER BY to sort data in descending order.SELECT column1, column2, … FROM table_name ORDER BY column1, column2, … DESC
CHECKConstrains the value which can be added to a column.CREATE TABLE student(fullName varchar(255), age INT, CHECK(age >= 18))
CREATE DATABASECreates a new database.CREATE DATABASE student;
DEFAULTSets the default value for a given column.CREATE TABLE products(ID int, name varchar(255) DEFAULT ‘Username’, from date DEFAULT GETDATE())
DELETEDelete values from a table.DELETE FROM users WHERE user_id= 674
DROP COLUMNDeletes/Drops a column from a table.ALTER TABLE student DROP COLUMN name
DROP DATABASECompletely deletes a database with all its content within.DROP DATABASE student
DROP DEFAULTRemoves a default value for a column.ALTER TABLE student ALTER COLUMN age DROP DEFAULT
DROP TABLEDeletes a table from a database.DROP TABLE students
FROMDetermines which table to read or delete data from.SELECT * FROM students
INUsed with WHERE clause for multiple OR conditionals.SELECT * FROM students WHERE name IN(‘Scaler’, ‘Interviewbit’,‘Academy’)
ORDER BYUsed to sort given data in Ascending or Descending order.SELECT * FROM student ORDER BY age ASC
SELECT DISTINCTWorks in the same war as SELECT, except that only unique values are included in the results.SELECT DISTINCT age from student
TOPUsed in conjunction with SELECT to select a fixed number of records from a table.SELECT TOP 5 * FROM students
VALUESUsed along with the INSERT INTO keyword to add new values to a table.INSERT INTO Customers (CustomerName, City, Country) VALUES (‘Cardinal’, ‘Stavanger’, ‘Norway’)
WHEREFilters given data based on some given condition.SELECT * FROM students WHERE age >= 18
UNIQUEEnsures that all values in a column are different.UNIQUE (ID)
UNIONUsed to combine the result-set of two or more SELECT statements.SELECT column_name(s) FROM Table1 UNION SELECT column_name(s) FROM Table2
UNION ALLCombines the result set of two or more SELECT statements(it allows duplicate values)SELECT City FROM table1 UNION ALL SELECT City FROM table2 ORDER BY City;
SELECT TOPUsed to specify the number of records to return.SELECT TOP 3 * FROM Students
LIMITPuts a restriction on how many rows are returned from a query.SELECT * FROM table1 LIMIT 3
UPDATEModifies the existing records in a table.UPDATE Customers SET ContactName = ‘Scaler’, City = ‘India’ WHERE CustomerID = 1;
SETUsed with UPDATE to specify which columns and values should be updated in a table.UPDATE Customers SET ContactName = ‘Scaler’, City= ‘India’ WHERE
IS NULLColumn values are tested for NULL values using this operator.SELECT CustomerName, ContactName, Address FROM Customers WHERE Address IS NULL
LIKEUsed to search for a specified pattern in a column.SELECT * FROM Students WHERE Name LIKE ‘a%’
ROWNUMReturns a number indicating the order in which Oracle selects the row from a table or set of joined rows.SELECT * FROM Employees WHERE ROWNUM < 10;
GROUP BYGroups rows that have the same values into summary rows.SELECT COUNT(StudentID), State FROM Students GROUP BY State
HAVINGEnables the user to specify conditions that filter which group results appear in the results.HAVING COUNT(CustomerID) > 5

Clauses in SQL

NameDescriptionExample
WHEREUsed to select data from the database based on some conditions.SELECT * from Employee WHERE age >= 18;
ANDUsed to combine 2 or more conditions and returns true if all the conditions are True.SELECT * from Employee WHERE age >= 18 AND salary >= 45000 ;
ORSimilar to AND but returns true if any of the conditions are True.Select * from Employee where salary >= 45000 OR age >= 18
LIKEUsed to search for a specified pattern in a column.SELECT * FROM Students WHERE Name LIKE ‘a%’;
LIMITPuts a restriction on how many rows are returned from a query.SELECT * FROM table1 LIMIT 3;
ORDER BYUsed to sort given data in Ascending or Descending order.SELECT * FROM student ORDER BY age ASC
GROUP BYGroups rows that have the same values into summary rows.SELECT COUNT(StudentID), State FROM Students GROUP BY State;
HAVINGIt performs the same as the WHERE clause but can also be used with aggregate functions.SELECT COUNT(ID), AGE FROM Students GROUP BY AGE HAVING COUNT(ID) > 5;

SQL Operators

There are 3 main types of operators: Arithmetic, Comparision and Logical operators, each of which will be described below.

Arithmetic Operators

Arithmetic Operators allows the user to perform arithmetic operations in SQL. The table below shows the list of arithmetic operators available in SQL:

OperatorDescription
+Addition
-Subtraction
*Multiplication
/Division
%Modulo

Bitwise Operators

Bitwise operators are used to performing Bit manipulation operations in SQL. The table below shows the list of bitwise operators available in SQL:

OperatorDescription
&Bitwise AND
!|Bitwise OR
^Bitwise XOR

Relational Operators

Relational operators are used to performing relational expressions in SQL, i.e those expressions whose value either result in true or false. The table below shows the list of relational operators available in SQL:

OperatorDescription
=Equal to
>Greater than
<Less than
>=Greater than or equal to
<=Less than or equal to
<>Not equal to

Compound Operators

Compound operators are basically a combination of 2 or more arithmetic or relational operator, which can be used as a shorthand while writing code. The table below shows the list of compound operators available in SQL:

OperatorDescription
+=Add equals
-=Subtract equals
*=Multiply equals
/=Divide equals
%=Modulo equals
&=AND equals
!|=OR equals
^=XOR equals

Logical Operators

Logical operators are used to combining 2 or more relational statements into 1 compound statement whose truth value is evaluated as a whole. The table below shows the SQL logical operators with their description:

OperatorDescription
ALLReturns True if all subqueries meet the given condition.
ANDReturns True if all the conditions turn out to be true
ANYTrue if any of the subqueries meet the given condition
BETWEENTrue if the operand lies within the range of the conditions
EXISTSTrue if the subquery returns one or more records
INReturns True if the operands to at least one of the operands in a given list of expressions
LIKEReturn True if the operand and some given pattern match.
NOTDisplays some record if the set of given conditions is False
ORReturns True if any of the conditions turn out to be True
SOMEReturns True if any of the Subqueries meet the given condition.

Function in sql

SQL Server Numeric Functions

The table below lists some of the Numeric functions in SQL with their description:

NameDescription
ABSReturns the absolute value of a number.
ASINReturns arc sine value of a number.
AVGReturns average value of an expression.
COUNTCounts the number of records returned by a SELECT query.
EXPReturns e raised to the power of a number.
FLOORReturns the greatest integer <= the number.
RANDReturns a random number.
SIGNReturns the sign of a number.
SQRTReturns the square root of a number.
SUMReturns the sum of a set of values.

SQL Server Date Functions

The table below lists some of the Date functions in SQL with their description:

NameDescription
CURRENT_TIMESTAMPReturns current date and time.
DATEADDAdds a date/time interval to date and returns the new date.
DATENAMEReturns a specified part of a date(as a string).
DATEPARTReturns a specified part of a date(as an integer).
DAYReturns the day of the month for a specified date.
GETDATEReturns the current date and time from the database.

SQL Server Advanced Functions

The table below lists some of the Advanced functions in SQL with their description:

NameDescription
CASTTypecasts a value into specified datatype.
CONVERTConverts a value into a specified datatype.
IIFReturn a value if a condition evaluates to True, else some other value.
ISNULLReturn a specified value if the expression is NULL, else returns the expression.
ISNUMERICChecks if an expression is numeric or not.
SYSTEM_USERReturns the login name for the current user
USER_NAMEReturns the database user name based on the specified id.

Joins in SQL

COMMANDSYNTAXDESCRIPTION
INNER JOINSELECT column_name(s) FROM table1 INNER JOIN table2 ON table1.column_name = table2.column_name;selects records that have matching values in both tables.
LEFT JOINSELECT column_name(s) FROM table1 LEFT JOIN table2 ON table1.column_name = table2.column_name;returns all records from the left table (table1), and the matching records from the right table (table2). The result is 0 records from the right side, if there is no match.
RIGHT JOINSELECT column_name(s) FROM table1 RIGHT JOIN table2 ON table1.column_name = table2.column_name;returns all records from the right table (table2), and the matching records from the left table (table1). The result is 0 records from the left side, if there is no match.
FULL JOINSELECT column_name(s) FROM table1 FULL OUTER JOIN table2 ON table1.column_name = table2.column_name WHERE condition;returns all records when there is a match in left (table1) or right (table2) table records.
SELF JOINSELECT column_name(s) FROM table1 T1, table1 T2 WHERE condition;A self join is a regular join, but the table is joined with itself.