MySQL Queries 13
MySQL Queries 13
The GROUP BY clause is used to arrange the rows in a group using a particular column value. If there
are multiple rows with the same value for a column then all those rows will be grouped with that column
value. It is used with the SELECT statement and is placed after the WHERE clause and before the
ORDER BY if used any.
Syntax:
SELECT column1,column2,…
FROM table_name
WHERE condition
GROUP BY column1,column2, …
Order BY column1, column2, ….
The GROUP BY clause is generally used with aggregate functions like SUM, AVG, COUNT, MAX,
MIN. The aggregate functions provide information about each group.
cricketers
Virat 33 India
Rohit 34 India
Stokes 30 England
Finch 35 Australia
Warner 35 Australia
For example:
SELECT country
FROM cricketers
GROUP BY country;
Output:
country
India
South Africa
New Zealand
England
Australia
In the above example, the country is selected and grouped according to the country which ensures
unique occurrences of each country.
For example:
Output:
number_of_players country
2 India
1 South Africa
2 New Zealand
1 England
2 Australia
Similarly, when GROUP BY is used with multiple columns, all those rows will be grouped which have
the same value for all the columns used for grouping.
HAVING
The HAVING clause is used with the GROUP BY clause in a query to specify come conditions and
filter some groups or aggregates that fulfill those conditions. The difference between WHERE and
HAVING is, WHERE is used to filter rows, and HAVING is used to filter groups by applying some
conditions.
Syntax:
SELECT column1, column2, …
FROM table_name
WHERE conditions
GROUP BY column1, column2, …..
HAVING conditions
For example:
cricketers
Virat 33 India
Rohit 34 India
Stokes 30 England
Finch 35 Australia
Warner 35 Australia
Output:
number_of_players country
2 India
2 New Zealand
2 Australia
In the above example, the players are grouped according to their country and those countries which have
the number of players >1 are selected using the HAVING clause
GROUP BY
The GROUP BY clause is used to arrange the rows in a group using a particular column value. If there
are multiple rows with the same value for a column then all those rows will be grouped with that column
value. It is used with the SELECT statement and is placed after the WHERE clause and before the
ORDER BY if used any.
Syntax:
SELECT column1,column2,…
FROM table_name
WHERE condition
GROUP BY column1,column2, …
Order BY column1, column2, ….
The GROUP BY clause is generally used with aggregate functions like SUM, AVG, COUNT, MAX,
MIN. The aggregate functions provide information about each group.
cricketers
Virat 33 India
Rohit 34 India
Stokes 30 England
Finch 35 Australia
Warner 35 Australia
For example:
SELECT country
FROM cricketers
GROUP BY country;
Output:
country
India
South Africa
New Zealand
country
England
Australia
In the above example, the country is selected and grouped according to the country which ensures
unique occurrences of each country.
For example:
Output:
number_of_players country
2 India
1 South Africa
2 New Zealand
1 England
2 Australia
Similarly, when GROUP BY is used with multiple columns, all those rows will be grouped which have
the same value for all the columns used for grouping.
HAVING
The HAVING clause is used with the GROUP BY clause in a query to specify come conditions and
filter some groups or aggregates that fulfill those conditions. The difference between WHERE and
HAVING is, WHERE is used to filter rows, and HAVING is used to filter groups by applying some
conditions.
Syntax:
cricketers
Virat 33 India
Rohit 34 India
Stokes 30 England
Finch 35 Australia
Warner 35 Australia
Output:
number_of_players country
2 India
2 New Zealand
2 Australia
In the above example, the players are grouped according to their country and those countries which have
the number of players >1 are selected using the HAVING clause
. SELECT Statement
The SELECT statement in SQL is used to retrieve data from one or more tables in a database. It is a
fundamental and powerful command that allows you to query and display information stored in a
relational database.
Example:
1. SELECT * FROM employees; (* gives you the complete data of the table).
2. SELECT first_name, last_name FROM employees; (gives you all the data of the first name and last
name from the table employees).
2. SELECT DISTINCT
The SELECT DISTINCT statement is used to retrieve unique values from a specific column in a table. It
eliminates duplicate rows and returns only distinct values.
Syntax: SELECT DISTINCT column1, column2, ... FROM table_name WHERE condition;
Example:
1. SELECT DISTINCT first_name, last_name FROM students; (gives you the unique values of the first
name and last name from the table students).
3. WHERE Clause
The WHERE clause in SQL is used to filter the rows returned by a SELECT statement based on a specified
condition. It allows you to retrieve only the rows that meet certain criteria.
Example:
1. SELECT * FROM students WHERE age > 20; (gives you the data of students whose age is above
20).
4. ORDER BY Clause
The ORDER BY clause in SQL is used to sort the result set of a SELECT statement based on one or more
columns. It allows you to specify the order in which the rows should be displayed, either in ascending
(default) or descending order.
Syntax: SELECT column1, column2, ... FROM table_name ORDER BY column1 [ASC | DESC],
column2 [ASC | DESC], ...;
Example:
1. SELECT * FROM students ORDER BY age; (organizes the data of the table by age in
ascending/descending order).
The LIMIT and OFFSET clauses in SQL are used to control the number of rows returned by a SELECT
statement, allowing you to retrieve a specific subset of the result set. These clauses are often used
together to implement pagination or to fetch a limited number of rows starting from a certain position.
Example:
1. SELECT * FROM students LIMIT 2 OFFSET 2; (the LIMIT 2 restricts the result set to two rows, and
the OFFSET 2 skips the first two rows.)
6. INSERT Statement
The INSERT statement in SQL is used to insert new records (rows) into a table. It adds data to an
existing table by specifying the values to be inserted into each column.
Syntax: INSERT INTO table_name (column1, column2, …) VALUES (value1, value2, …);
Example:
1. INSERT INTO students (student_id, first_name, last_name, age, grade) VALUES (7, ‘Alice’,
‘Johnson’, 21, ‘B’); (adds a new student to the students’ table with the required details).
7. UPDATE Statement
The UPDATE statement in SQL is used to modify existing records (rows) in a table. It allows you to
change the values of one or more columns in the specified rows based on a specified condition.
Syntax: UPDATE table_name SET column1 = value1, column2 = value2, … WHERE condition;
Example:
1. UPDATE students SET age = 20, grade = ‘B’ WHERE student_id = 3; (update the students’ table
with the student’s age as 20, grade as B where id is 3).
8. DELETE Statement
The DELETE statement in SQL is used to remove records (rows) from a table based on a specified
condition. It permanently removes data from the table.
Example:
1. DELETE FROM students WHERE student_id = 4; (deletes the entire data of student whose id is 4
from the table students).
9. COUNT() Function
The COUNT function in SQL is used to count the number of rows in a table or the number of rows that
satisfy a particular condition in a specified column.
Example:
1. SELECT COUNT(*) FROM students; (displays the count of total number of students from the table
students).
The SUM function in SQL is used to calculate the sum of values in a numeric column, typically within a
specified group or for all rows in a table.
Example:
1. SELECT SUM(amount) FROM sales; (displays the total amount from the sales table).
The GROUP BY clause in SQL is used to group rows that have the same values in specified columns into
summary rows, like “total sales per product” or “average score per student.” It’s often used with
aggregate functions like SUM, COUNT, AVG, etc.
Example:
1. SELECT product, SUM(amount) as total_sales FROM sales GROUP BY product; (groups the data
by the “product” column and displays the result.)
The HAVING clause in SQL is used in conjunction with the GROUP BY clause to filter the results of a
grouped query. While the WHERE clause filters rows before grouping, the HAVING clause filters groups
after the grouping has taken place. It is commonly used with aggregate functions like SUM, COUNT, AVG,
etc.
In SQL, the JOIN statement is used to combine rows from two or more tables based on a related column
between them.
There are different types of joins, including INNER JOIN, LEFT JOIN (or LEFT OUTER JOIN), RIGHT
JOIN (or RIGHT OUTER JOIN), and FULL JOIN (or FULL OUTER JOIN).
Example:
14. Subqueries
A subquery, also known as a nested query or inner query, is a query embedded within another query. It
can be used to retrieve data that will be used in the main query as a condition to further restrict the data
to be retrieved. Subqueries can be used in various parts of a SQL statement, including the SELECT,
FROM, WHERE, and HAVING clauses.
Syntax: SELECT column1, column2, … FROM table_name WHERE column_name operator (SELECT
column_name FROM another_table WHERE condition);
Example:
1. SELECT first_name FROM students WHERE student_id IN (SELECT student_id FROM grades
WHERE grade = ‘A’); (it finds the student_id values from the “grades” table where the grade is ‘A’.
The main query then selects the first_name of students whose student_id is in the result set of the
subquery.)
15. Views
A view is a virtual table based on the result of a SELECT query. It allows you to simplify complex
queries, encapsulate logic, and present a subset or transformation of the data to users without exposing
the underlying table structure.
Views are often used to enhance data security by restricting direct access to certain tables and providing
a controlled way to access specific data.
Syntax: CREATE VIEW view_name AS SELECT column1, column2, … FROM table_name WHERE
condition;
Example:
Write, Run & Share MySQL queries online using OneCompiler's MySQL online editor and compiler for
free. It's one of the robust, feature-rich online editor and compiler for MySQL. Getting started with the
OneCompiler's MySQL editor is really simple and pretty fast. The editor shows sample boilerplate code
when you choose language as 'MySQL' and start writing queries to learn and test online without
worrying about tedious process of installation.
About MySQL
MySQL is a open-source, free and very popular relational database management system which is
developed, distributed and supported by Oracle corporation.
Key Features:
Syntax help
Commands
CREATE TABLE STUDENT(
REG_NO CHAR(5),
SNAME VARCHAR(15),
AGE INTEGER(2),
DEPT VARCHAR(10),
CLASS CHAR(3)
);
-- VIEW TABLE STRUCTURE
DESC STUDENT;
-- INSERTING DATA INTO TABLE
INSERT INTO STUDENT
VALUES('M1001','HARISH',19,'ME','ME1');
INSERT INTO STUDENT
VALUES('M1002','AKASH',20,'ME','ME2');
INSERT INTO STUDENT
VALUES('C1001','SNEHA',20,'CSE','CS1');
INSERT INTO STUDENT
VALUES('C1002','LITHYA',19,'CSE','CS2');
INSERT INTO STUDENT
VALUES('E1001','RAVI',20,'ECE','EC1');
INSERT INTO STUDENT
VALUES('E1002','LEENA',21,'EEE','EE1');
INSERT INTO STUDENT
VALUES('E1003','ROSE',20,'ECE','EC2');
-- VIEW ALL RECORDS:
SELECT*FROM STUDENT;
-- OTHER QURIES:
-- LISTING THE STUDENTS WHOSE DEPART MENT IS
CSE:
SELECT*FROM STUDENT WHERE DEPT='CSE';
-- LIST ALL THE STUDENTS WHERE AGE 20 AND MORE
IN ME DEPARTMENT
SELECT*FROM STUDENT WHERE AGE>=20 AND
DEPT='ME';
-- LIST THE STUDENTS DEPARTMENT WISE:
SELECT*FROM STUDENT GROUP BY DEPT ORDER BY
SNAME;
-- MODIFY THE CLASS ME2 TO ME1:
UPDATE STUDENT SET CLASS='ME1' WHERE
CLASS='ME2';
SELECT*FROM STUDENT;
-- CHECK THE UNIQUENESS OF REGISTER NO:
SELECT DISTINCT REG_NO FROM STUDENT;
1. CREATE
CREATE TABLE table_name (
column1 datatype,
column2 datatype,
....);
Example
CREATE TABLE EMPLOYEE (
empId INTEGER PRIMARY KEY,
name TEXT NOT NULL,
dept TEXT NOT NULL
);
2. ALTER
ALTER TABLE Table_name ADD column_name datatype;
Example
INSERT INTO EMPLOYEE VALUES (0001, 'Dave', 'Sales');
3. TRUNCATE
TRUNCATE table table_name;
4. DROP
DROP TABLE table_name;
5. RENAME
RENAME TABLE table_name1 to new_table_name1;
6. COMMENT
Single-Line Comments:
--Line1;
Multi-Line comments:
/* Line1,
Line2 */
DML Commands
1. INSERT
INSERT INTO table_name (column1, column2, column3, ...) VALUES (value1, value2,
value3, ...);
Example
INSERT INTO EMPLOYEE VALUES (0001, 'Ava', 'Sales');
2. SELECT
SELECT column1, column2, ...
FROM table_name
[where condition];
Example
SELECT * FROM EMPLOYEE where dept ='sales';
3. UPDATE
UPDATE table_name
SET column1 = value1, column2 = value2, ...
WHERE condition;
Example
UPDATE EMPLOYEE SET dept = 'Sales' WHERE empId='0001';
4. DELETE
DELETE FROM table_name where condition;
Example
DELETE from EMPLOYEE where empId='0001';
Indexes
1. CREATE INDEX
CREATE INDEX index_name on table_name(column_name);
Views
1. Create a View
Creating a View:
CREATE VIEW View_name AS
Query;
3. Altering a View
ALTER View View_name AS
Query;
4. Deleting a View
DROP VIEW View_name;
Triggers
1. Create a Trigger
CREATE TRIGGER trigger_name trigger_time trigger_event
ON tbl_name FOR EACH ROW [trigger_order] trigger_body
/* where
trigger_time: { BEFORE | AFTER }
trigger_event: { INSERT | UPDATE | DELETE }
trigger_order: { FOLLOWS | PRECEDES } */
2. Drop a Trigger
DROP TRIGGER [IF EXISTS] trigger_name;
Stored Procedures
1. Create a Stored Procedure
CREATE PROCEDURE sp_name(p1 datatype)
BEGIN
/*Stored procedure code*/
END;
Joins
1. INNER JOIN
SELECT * FROM TABLE1 INNER JOIN TABLE2 where condition;
2. LEFT JOIN
SELECT * FROM TABLE1 LEFT JOIN TABLE2 ON condition;
3. RIGHT JOIN
SELECT * FROM TABLE1 RIGHT JOIN TABLE2 ON condition;
4. CROSS JOIN
SELECT select_list from TABLE1 CROSS JOIN TABLE2;
The data-driven world of today requires a lot of data to function. A majority of the data is stored as
databases, which is an organized collection of data. A database management system or DBMS in short
acts as a bridge between the database and end-user to ensure that the data is well organized and easily
accessible. A DBMS assists in optimizing, storing, retrieving, and managing data in databases.
MySQL is the most widely used database management system software for managing relational
databases today. It is an open-source database that is supported by the Oracle Corporation. When
compared to Microsoft SQL Server and Oracle Database, it is a quick, scalable, and simple to use
database management system. It’s frequently combined with backend languages to build powerful and
dynamic server-side or web-based enterprise applications. MySQL AB, a Swedish business, created,
marketed, and supported it, and it was written in the C and C++ programming languages. Many small
and large businesses use MySQL. It supports a variety of operating systems, including Windows, Linux,
macOS, and others. MySQL is a Relational Database Management System (RDBMS) that offers a
variety of features, including:
It allows us to use tables, rows, columns, and indexes and to perform database operations on them.
Tables (collection of rows and columns), also known as relations, are used to construct database
relationships.
It ensures that the Referential Integrity (referential integrity is an RDBMS concept which states that any
foreign key field must agree with the primary key that is referenced by the foreign key) between rows or
columns of different tables is maintained.
It automatically updates the table indexes as soon as a record is changed.
It employs a number of SQL queries and integrates useful data from many columns and rows for end-
users.
This article covers all the most frequently used commands and statements. With this handy collection of
MySQL commands, you’ll be able to operate more efficiently and effectively with your MySQL
databases. You’ll see at a glance the most commonly used commands and statements you need for
creating and managing the databases in MySQL.
Table Of Contents
show
MySQL commands
o Working with databases
o Working with tables
o Working with indexes
o Working with views
o Working with stored procedures
o Querying data from tables
o Join
Inner Join
Left join
o Modifying data in tables
o Searching
o MySQL command-line client commands
Conclusion
Frequently Asked Questions
Additional Resources
MySQL commands
Working with databases
A database is a collection of organized records that the user can conveniently access and manage. It
organizes the data into tables, rows, columns, and indexes to make it easier to retrieve the information
we need quickly. Let’s try to build a student database using the following command.
The following syntax can create a database. It also verifies whether the database name is already in
use.
Use the following syntax to replace the current database with another database you’re working on:
Using the following syntax, we can permanently destroy a database and its associated files. All the
tables that are a part of that database will be deleted if we use the following command.
Use the following syntax to display all databases on the current server:
mysql> SHOW DATABASES;
As you can see in the snapshot above, we created a database named ‘students’ using create command,
and deleted a database named class using DROP command.
A table in a database is a collection of related data organized in a table structure. It’s made up of
columns and rows. A table is a collection of data components in relational and flat-file databases that
uses a model of vertical columns and horizontal rows, with the cell being the unit where a row and
column intersect.
MARKS TABLE
ID Name Marks
001 Ashish 94
002 Bharat 81
003 Deepak 78
004 Fatima 92
Assume we have a contact book with the users’ names and phone numbers. We’re looking for a phone
number in this contact book. If the contact book is in an unordered manner, which means the names
aren’t organized alphabetically, we’ll have to go through all the pages and read every name until we
don’t locate the requested name. Sequential searching is the name for this form of search. While this
approach is correct, applying this in a large database will consume a lot of time. In this situation,
database indexing aids in the retrieval of the desired result and increases the query’s overall
performance.
Indexes are used to quickly locate records with certain column values. It is similar to the index given in
a book, you can easily locate a chapter using the index of the book.
A unique index ensures that the index key includes no duplicate values, ensuring that each entry in the
table is distinct in some sense. To create a unique index, use the following syntax:
CREATE UNIQUE INDEX index_name
ON table_name (column,…);
A view is a database object that doesn’t have any data in it. Its contents are based on the table that serves
as the foundation. It has the same rows and columns as a genuine table. In MySQL, a View is a virtual
table that is produced by connecting one or more tables in a query. It works in the same way as the base
table, but it doesn’t have any data of its own. The fundamental distinction between a view and a table is
that views are definitions constructed on top of other tables (or views).
Let’s try to understand it with an example. We are going to create a view from the Marks table
mentioned above.
We can use SELECT to see the actual view, just like what we do with tables.
Rename a view:
RENAME TABLE view_name
TO new_view_name;
A stored procedure is a piece of prepared SQL code that you can save and reuse over and over. So, if
you have a SQL query that you create frequently, save it as a stored procedure and then call it to run it.
You can also pass parameters to a stored procedure so that it can act based on the value(s) of the
parameter(s) passed.In the normal computing language, it is a subroutine or a subprogram. MySQL
version 5 was the first to include it. It is currently supported by nearly all relational database systems.
Let’s try to create a procedure. We will create a procedure that shows all the students who have scored
an A grade (90+ marks).
First, open MySQL workbench and select the database (students database in our case). Then we have to
store our procedure.
You can also create and store functions with parameters using the syntax:
DELIMITER $$
CREATE FUNCTION function_name(parameter_list)
RETURNS datatype
[NOT] DETERMINISTIC
BEGIN
— statements
END $$
DELIMITER ;
A query is any command used to retrieve data from a table in relational database management systems.
The SELECT statement is most often used in Structured Query Language (SQL) queries. Select is a type
of DQL (Data Query Language) command. DQL statements are used to perform queries.
For example, to query the entire contents of a table, use the following command:
SELECT * FROM table_name;
The above query will return each record of the given table.
For example:
If you want MySQL to show only some columns of the table, you can use the following syntax:
SELECT
column1, column2, …
FROM
Table_name;
We can filter records using WHERE clause. It returns only those records which fulfill a specified set of
condition.
SELECT column_list
FROM table_name
WHERE condition;
For example, if we want to write a query to retrieve the name of students whose score is less than 80, it
will look something like this:
SELECT Name from Marks
WHERE Marks <80;
You can change the output of the column name using column alias:
SELECT
column1 AS alias_name,
expression AS alias,
…
FROM
Table_name;
The name of the column will be changed to alias_name in the result (not in the actual table).
You can sort a result set in ascending and descending order by writing the following code::
SELECT
select_list
FROM
table_name
ORDER BY
column1 ASC [DESC],
column2 ASC [DESC];
Join
In a join, you can get records from two (or more) logically connected tables in one result set. JOIN
clauses are used to return the rows of two or more queries that use two or more tables that have a
meaningful relationship based on a set of values in common. These values are normally the same
column name and datatype that occur in both of the connected tables. The join key is usually, but not
always, the primary key of one table and a foreign key in another table. As long as the data in the
columns matches, the join can be executed.
members_id name
1 John
2 Jane
3 Mary
4 David
5 Amelia
committee_id name
1 John
2 Mary
3 Amelia
4 Joe
Inner Join
Each row from the first table is compared to every record from the second table in the inner join clause.
If the join condition is met in both rows, the inner join clause creates a new row with a column that
contains all columns from both tables and includes it in the result set. In other words, only matched rows
from both tables are included in the inner join clause. Each row from the first table is compared to every
record from the second table in the inner join clause.
To query data from multiple tables using inner join, use the following command:
SELECT select_list
FROM table1
INNER JOIN table2 ON condition;
FROM
members m
INNER JOIN committees c ON c.name = m.name;
It will produce the following result:
1 John 1 John
3 Mary 2 Mary
5 Amelia 3 Amelia
Left join
A join predicate is required for a left join, just as it is for an inner join.The left join selects data from the
table on the left. The left join compares every row in the left table to every row in the right table. The
left join clause creates a new row whose columns comprise all columns of the rows in both tables if the
values in the two rows satisfy the join condition, and includes this row in the result set. The left join
clause still creates a new row whose columns contain columns from the left table and NULL for
columns from the right table if the values in the two rows do not match.
You can query data from multiple tables using left join by using the following syntax:
SELECT select_list
FROM table1
LEFT JOIN table2 ON condition;
FROM
members m
LEFT JOIN committees c USING(name);
The resulting table will look like this:
1 John 1 John
3 Mary 2 Mary
5 Amelia 3 Amelia
The right join clause is similar to the left join clause, with the exception that the left and right tables are
treated differently. Instead of selecting data from the left table, the right join selects data from the right
table.
You can query data from multiple tables using the right join:
SELECT select_list
FROM table1
RIGHT JOIN table2 ON condition;
FROM
members m
RIGHT JOIN committees c on c.name = m.name;
3 Mary 2 Mary
5 Amelia 3 Amelia
A Cartesian product of rows from the joined tables is created by the cross join. To create the result set,
the cross join joins every row from the first table with every row from the right table. Let’s say there are
n rows in the first table and m rows in the second table. The nxm rows will be returned by the cross join
that joins the tables.
Syntax:
SELECT select_list
FROM table1
CROSS JOIN table2;
In order to cross join our two tables, the syntax will look like this:
SELECT
m.member_id,
m.name AS member,
c.committee_id,
c.name AS committee
FROM
members m
CROSS JOIN committees c;
Searching
LIKE and RLIKE clauses are used to search desired records from the table.
The SQL LIKE clause compares a value to other values that are similar using wildcard operators. With
the LIKE operator, there are two wildcards that can be used.
The % sign can be used to indicate zero, one, or more characters. A single number or letter is
represented by the underscore. These symbols can be mixed and matched.
The syntax for LIKE clause
SELECT select_list
FROM table_name
WHERE column LIKE ‘%pattern%’ (or ‘_ABC’);
E.g, ‘S%’ will fetch all values that start with S.
‘_AB’ will fetch all values that have A and B at second and third places respectively.
In MySQL, this operator is used to pattern match a string expression against a pattern.
Syntax:
SELECT select_list
FROM table_name
WHERE column RLIKE ‘regular_expression’;
exit;
To exit MySQL command line.
mysql> system clear;
On Linux, type the above command to clear the MySQL screen console window.
On Windows OS, there is currently no command to clear the MySQL screen console.
SQL Commands: The Complete List (w/ Examples)
To get a data job, you are going to need to learn SQL. The common SQL commands and operators
discussed in this post are a great reference. If you're looking for more details and SQL resources, check
out our Complete guide to SQL.
Below is a comprehensive list of SQL commands, organized by the top-level of each (e.g. SELECT
TOP is within the SELECT category).
If you’re on a journey to learn SQL and you’ve been frustrated by the lack of structure or the dull
curriculum, then you may like Dataquest’s interactive SQL skill path. Try it free.
SELECT is probably the most commonly-used SQL statement. You'll use it pretty much every time you
query data with SQL. It allows you to define what data you want your query to return.
For example, in the code below, we’re selecting a column called name from a table called customers.
SELECT name
FROM customers;
SELECT *
SELECT used with an asterisk (*) will return all of the columns in the table we're querying.
SELECT DISTINCT
SELECT DISTINCT only returns data that is distinct — in other words, if there are duplicate records, it
will return only one copy of each.
The code below would return only rows with a unique name from the customers table.
SELECT INTO copies the specified data from one table into another.
SELECT TOP
SELECT TOP only returns the top x number or percent from a table.
The code below would return the top 50 results from the customers table:
The code below would return the top 50 percent of the customers table:
AS
AS renames a column or table with an alias that we can choose. For example, in the code below, we’re
renaming the name column as first_name:
FROM
SELECT name
FROM customers;
WHERE
WHERE filters your query to only return results that match a set condition. We can use this together
with conditional operators like =, >, <, >=, <=, etc.
SELECT name
FROM customers
WHERE name = ‘Bob’;
AND
AND combines two or more conditions in a single query. All of the conditions must be met for the result
to be returned.
SELECT name
FROM customers
WHERE name = ‘Bob’ AND age = 55;
OR
OR combines two or more conditions in a single query. Only one of the conditions must be met for a
result to be returned.
SELECT name
FROM customers
WHERE name = ‘Bob’ OR age = 55;
BETWEEN
BETWEEN filters your query to return only results that fit a specified range.
SELECT name
FROM customers
WHERE age BETWEEN 45 AND 55;
LIKE
LIKE searches for a specified pattern in a column. In the example code below, any row with a name that
included the characters Bob would be returned.
SELECT name
FROM customers
WHERE name LIKE ‘%Bob%’;
IN
IN allows us to specify multiple values we want to select for when using the WHERE command.
SELECT name
FROM customers
WHERE name IN (‘Bob’, ‘Fred’, ‘Harry’);
IS NULL
SELECT name
FROM customers
WHERE name IS NULL;
IS NOT NULL
IS NOT NULL does the opposite — it will return only rows without a NULL value.
SELECT name
FROM customers
WHERE name IS NOT NULL;
CREATE
CREATE DATABASE
CREATE DATABASE creates a new database, assuming the user running the command has the correct
admin rights.
CREATE TABLE
CREATE TABLE creates a new table inside a database. The terms int and varchar(255) in this
example specify the datatypes of the columns we're creating.
CREATE INDEX
CREATE INDEX generates an index for a table. Indexes are used to retrieve data from a database
faster.
CREATE VIEW
CREATE VIEW creates a virtual table based on the result set of an SQL statement. A view is like a
regular table (and can be queried like one), but it is not saved as a permanent table in the database.
DROP
It goes without saying that the DROP command should only be used where absolutely necessary.
DROP DATABASE
DROP DATABASE deletes the entire database including all of its tables, indexes etc as well as all the
data within it.
DROP TABLE
DROP INDEX
UPDATE
The UPDATE statement is used to update data in a table. For example, the code below would update the
age of any customer named Bob in the customers table to 56.
UPDATE customers
SET age = 56
WHERE name = ‘Bob’;
DELETE
DELETE can remove all rows from a table (using ), or can be used as part of a WHERE clause to delete
rows that meet a specific condition.
ALTER TABLE
ALTER TABLE allows you to add or remove columns from a table. In the code snippets below, we’ll
add and then remove a column for surname. The text varchar(255) specifies the datatype of the
column.
An aggregate function performs a calculation on a set of values and returns a single result.
COUNT
COUNT returns the number of rows that match the specified criteria. In the code below, we’re using *,
so the total row count for customers would be returned.
SELECT COUNT(*)
FROM customers;
SUM
SELECT SUM(age)
FROM customers;
AVG
SELECT AVG(age)
FROM customers;
MIN
SELECT MIN(age)
FROM customers;
MAX
SELECT MAX(age)
FROM customers;
GROUP BY
The GROUP BY statement groups rows with the same values into summary rows. The statement is
often used with aggregate functions. For example, the code below will display the average age for each
name that appears in our customers table.
HAVING
HAVING performs the same action as the WHERE clause. The difference is that HAVING is used for
aggregate functions, whereas WHERE doesn’t work with them.
The below example would return the number of rows for each name, but only for names with more than
2 records.
SELECT COUNT(customer_id), name
FROM customers
GROUP BY name
HAVING COUNT(customer_id) > 2;
ORDER BY
ORDER BY sets the order of the returned results. The order will be ascending by default.
SELECT name
FROM customers
ORDER BY age;
DESC
SELECT name
FROM customers
ORDER BY age DESC;
OFFSET
The OFFSET statement works with ORDER BY and specifies the number of rows to skip before
starting to return rows from the query.
SELECT name
FROM customers
ORDER BY age
OFFSET 10 ROWS;
FETCH
FETCH specifies the number of rows to return after the OFFSET clause has been processed. The
OFFSET clause is mandatory, while the FETCH clause is optional.
SELECT name
FROM customers
ORDER BY age
OFFSET 10 ROWS