Practical SQL Queries, Cheat Sheets, and Interview Q&A for Data Scientists

  • Nowadays, for professionals looking to build a career in data science, learning SQL is a must-have skill. Read more here.
  • This all-inclusive SQL server tutorial helps data scientists get started with SQL straight away through many simple practical examples and exercises (with answers). The best way we learn SQL is by practice.
  • The present tutorial also includes several important SQL basics cheat sheets, representing a quick guide to SQL commands and queries along with their examples and descriptions. 
  • In addition to numerous references and links to free online SQL resources, we have compiled a set of top SQL interview Q&A tailored to data scientists.

Become a SQL pro! Begin your SQL journey with confidence! 

Table of Contents

  1. MS SQL Server Requirements
  2. RDBMS
  3. SQL SELECT Statement
  4. SQL Quieries with Constraints
  5. SQL ORDER BY Statement
  6. The SQL AND/OR Operator
  7. Multi-Table INNER JOIN Queries
  8. Multi-Table OUTER JOIN Queries
  9. SQL Queries with Expressions
  10. SQL Queries with Aggregates
  11. SQL Cheat Sheets
  12. Interview Q&A
  13. Discussion
  14. Conclusions
  15. The Road Ahead
  16. Resources

MS SQL Server Requirements

  • For the sake of simplicity, we restrict ourselves to the MS SQL Server.
  • MS SQL Server requires a minimum of 6 GB of available hard-disk space.
  • Memory Express Editions: 1 GB.
  • Processor Speed x64 Processor: 1.4 GHz
  • Windows 10 TH1 1507 or greater with .NET Framework

RDBMS

  • RDBMS stands for Relational Database Management System.
  • The data in RDBMS is stored in database objects called tables.
  • A table is a data collection that consists of columns and rows (records).
  • A field is a column in a table that is designed to maintain specific information about every record in the table (Customer ID, Address, City, etc.).
  • A record is a horizontal entity in a table. A column is a vertical entity in a table that contains all information associated with a specific field in a table.

Example: Table Vehicles

Example table Vehicles

Key Takeaways:

  • A relational database represents a collection of related (two-dimensional) tables.
  • Each of the tables are similar to an Excel spreadsheet, with a fixed number of named columns (the attributes or properties of the table) and any number of rows of data.

SQL SELECT Statement

  • The SELECT statement is used to query the database and retrieve selected data that match the criteria that you specify:
SELECT [ALL | DISTINCT] column1[,column2] FROM table1[,table2] [WHERE "conditions"] [GROUP BY "column-list"] [HAVING "conditions] [ORDER BY "column-list" [ASC | DESC] ] 
Tablename	Records
Customers	91
Categories	8
Employees	10
OrderDetails	518
Orders	196
Products	77
Shippers	3
Suppliers	29
  • Example:
  • Return data from the Customers table
SELECT CustomerName,City FROM Customers;
  • Result:
  • Number of Records: 91
Result 
SELECT CustomerName,City FROM Customers;
  • Example: Select ALL columns
  • Return all the columns from the Customers table
SELECT * FROM Customers;
  • Result:
  • Number of Records: 91
Result:
SELECT * FROM Customers;
  • For the sake of completeness, we will also be using a database with data about some of Pixar’s classic movies for most of our exercises. This exercise will involve the Movies table, and the default query below currently shows all the properties of each movie:
SELECT * FROM movies;
  • Number of Records: 14

Table: Movies

Table Movies
  • Find the title of each film
SELECT title FROM movies;
Select the title of each film
  • Find the director of each film
SELECT director FROM movies;
Select the director of each film
  • Find the title and director of each film
SELECT title, director FROM movies; 
Find the title and director of each film
  • Find the title and year of each film
SELECT title, year FROM movies; 
Find the title and year of each film
  • Find all the information about each film
SELECT * FROM movies; 

See Table Movies above.

SQL Quieries with Constraints

SELECT * FROM Customers
WHERE Country='Mexico';
  • Result Number of Records: 5
SQL WHERE Clause example
  • Let’s look at the Movies table and find the movie with a row id of 6
SELECT id, title FROM movies 
WHERE id = 6;
  • Output
IdTitle
6The Incredibles
  • Table Movies: Find the movies released in the years between 2000 and 2010 
SELECT title, year FROM movies
WHERE year BETWEEN 2000 AND 2010;
  • Output
TitleYear
Monsters, Inc.2001
Finding Nemo2003
The Incredibles2004
Cars2006
Ratatouille2007
WALL-E2008
Up2009
Toy Story 32010
  • Table Movies: Find the movies not released in the years between 2000 and 2010
SELECT title, year FROM movies
WHERE year < 2000 OR year > 2010;
TitleYear
Toy Story1995
A Bug’s Life1998
Toy Story 21999
Cars 22011
Brave2012
Monsters University2013
  • Table Movies: Find all the Toy Story movies
SELECT title, director FROM movies 
WHERE title LIKE "Toy Story%";
TitleDirector
Toy StoryJohn Lasseter
Toy Story 2John Lasseter
Toy Story 3Lee Unkrich
  • Table Movies: Find all the movies directed by John Lasseter
SELECT title, director FROM movies 
WHERE director = "John Lasseter";
TitleDirector
Toy StoryJohn Lasseter
A Bug’s LifeJohn Lasseter
Toy Story 2John Lasseter
CarsJohn Lasseter
Cars 2John Lasseter
  • Table Movies: Find all the movies (and director) not directed by John Lasseter
SELECT title, director FROM movies 
WHERE director != "John Lasseter";
TitleDirector
Monsters, Inc.Pete Docter
Finding NemoAndrew Stanton
The IncrediblesBrad Bird
RatatouilleBrad Bird
WALL-EAndrew Stanton
UpPete Docter
Toy Story 3Lee Unkrich
BraveBrenda Chapman
Monsters UniversityDan Scanlon
WALL-GBrenda Chapman
  • Table Movies: Find all the WALL-* movies
SELECT * FROM movies 
WHERE title LIKE "WALL-_";
IdTitleDirectorYearLength_minutes
9WALL-EAndrew Stanton2008104
87WALL-GBrenda Chapman204297
  • Table Movies: List all directors of Pixar movies (alphabetically), without duplicates
SELECT DISTINCT director FROM movies
ORDER BY director ASC;
Director
Andrew Stanton
Brad Bird
Brenda Chapman
Dan Scanlon
John Lasseter
Lee Unkrich
Pete Docter

SQL ORDER BY Statement

  • Customers table: Sort the products by price
SELECT * FROM Products
ORDER BY Price;
  • Result Number of Records: 77
ProductIDProductNameSupplierIDCategoryIDUnitPrice
33Geitost154500 g2.5
24Guaraná Fantástica10112 – 355 ml cans4.5
13Konbu682 kg box6
52Filo Mix24516 – 2 kg boxes7
54Tourtière25616 pies7.45
75Rhönbräu Klosterbier12124 – 0.5 l bottles7.75
23Tunnbröd9512 – 250 g pkgs.9
19Teatime Chocolate Biscuits8310 boxes x 12 pieces9.2
45Røgede sild2181k pkg.9.5
47Zaanse koeken22310 – 4 oz boxes9.5
41Jack’s New England Clam Chowder19812 – 12 oz cans9.65
3Aniseed Syrup1212 – 550 ml bottles10
  • Customers table: Sort the products from highest to lowest price
SELECT * FROM Products
ORDER BY Price DESC;
  • Result Number of Records: 77
ProductIDProductNameSupplierIDCategoryIDUnitPrice
38Côte de Blaye18112 – 75 cl bottles263.5
29Thüringer Rostbratwurst12650 bags x 30 sausgs.123.79
9Mishi Kobe Niku4618 – 500 g pkgs.97
20Sir Rodney’s Marmalade8330 gift boxes81
18Carnarvon Tigers7816 kg pkg.62.5
59Raclette Courdavault2845 kg pkg.55
51Manjimup Dried Apples24750 – 300 g pkgs.53
62Tarte au sucre29348 pies49.3
43Ipoh Coffee20116 – 500 g tins46
28Rössle Sauerkraut12725 – 825 g cans45.6
27Schoggi Schokolade113100 – 100 g pieces43.9
63Vegie-spread7215 – 625 g jars43.9
8Northwoods Cranberry Sauce3212 – 12 oz jars40
17Alice Mutton7620 – 1 kg tins39
  • Customers table: Sort the products alphabetically by Product Name
SELECT * FROM Products
ORDER BY ProductName;
  • Result Number of Records: 77
ProductIDProductNameSupplierIDCategoryIDUnitPrice
17Alice Mutton7620 – 1 kg tins39
3Aniseed Syrup1212 – 550 ml bottles10
40Boston Crab Meat19824 – 4 oz tins18.4
60Camembert Pierrot28415 – 300 g rounds34
18Carnarvon Tigers7816 kg pkg.62.5
1Chais1110 boxes x 20 bags18
2Chang1124 – 12 oz bottles19
39Chartreuse verte181750 cc per bottle18
4Chef Anton’s Cajun Seasoning2248 – 6 oz jars22
5Chef Anton’s Gumbo Mix2236 boxes21.35
48Chocolade22310 pkgs.12.75
38Côte de Blaye18112 – 75 cl bottles263.5
58Escargots de Bourgogne27824 pieces13.25
  • Select all customers from the Customers table, sorted ascending by the “Country” and descending by the “Customer Name” column
SELECT * FROM Customers
ORDER BY Country ASC, CustomerName DESC;
  • Result Number of Records: 91
CustomerIDCustomerNameContactNameAddressCityPostalCodeCountry
64Rancho grandeSergio GutiérrezAv. del Libertador 900Buenos Aires1010Argentina
54Océano Atlántico Ltda.Yvonne MoncadaIng. Gustavo Moncada 8585 Piso 20-ABuenos Aires1010Argentina
12Cactus Comidas para llevarPatricio SimpsonCerrito 333Buenos Aires1010Argentina
59Piccolo und mehrGeorg PippsGeislweg 14Salzburg5020Austria
20Ernst HandelRoland MendelKirchgasse 6Graz8010Austria
76Suprêmes délicesPascale CartrainBoulevard Tirou, 255CharleroiB-6000Belgium
50Maison DeweyCatherine DeweyRue Joseph-Bens 532BruxellesB-1180Belgium
88Wellington ImportadoraPaula ParenteRua do Mercado, 12Resende08737-363Brazil
81Tradição HipermercadosAnabela DominguesAv. Inês de Castro, 414São Paulo05634-030Brazil
67Ricardo AdocicadosJanete LimeiraAv. Copacabana, 267Rio de Janeiro02389-890Brazil
62Queen CozinhaLúcia CarvalhoAlameda dos Canàrios, 891São Paulo05487-020Brazil

The SQL AND/OR Operator

  • Customers table: Select all customers from Spain that starts with the letter ‘G’
SELECT * FROM Customers
WHERE Country = 'Spain' AND CustomerName LIKE 'G%';

  • Result Number of Records: 2
CustomerIDCustomerNameContactNameAddressCityPostalCodeCountry
29Galería del gastrónomoEduardo SaavedraRambla de Cataluña, 23Barcelona08022Spain
30Godos Cocina TípicaJosé Pedro FreyreC/ Romero, 33Sevilla41101Spain
  • Customers table: Select all Spanish customers that starts with either “G” or “R”
SELECT * FROM Customers
WHERE Country = 'Spain'
AND (CustomerName LIKE 'G%' OR CustomerName LIKE 'R%');
  • Result Number of Records: 3
CustomerIDCustomerNameContactNameAddressCityPostalCodeCountry
29Galería del gastrónomoEduardo SaavedraRambla de Cataluña, 23Barcelona08022Spain
30Godos Cocina TípicaJosé Pedro FreyreC/ Romero, 33Sevilla41101Spain
69Romero y tomilloAlejandra CaminoGran Vía, 1Madrid28001Spain
  • Customers table: Select all customers from Germany or Spain
SELECT *
FROM Customers
WHERE Country = 'Germany' OR Country = 'Spain';
  • Result Number of Records: 16
CustomerIDCustomerNameContactNameAddressCityPostalCodeCountry
1Alfreds FutterkisteMaria AndersObere Str. 57Berlin12209Germany
6Blauer See DelikatessenHanna MoosForsterstr. 57Mannheim68306Germany
8Bólido Comidas preparadasMartín SommerC/ Araquil, 67Madrid28023Spain
17Drachenblut DelikatessendSven OttliebWalserweg 21Aachen52066Germany
22FISSA Fabrica Inter. Salchichas S.A.Diego RoelC/ Moralzarzal, 86Madrid28034Spain
25FrankenversandPeter FrankenBerliner Platz 43München80805Germany
29Galería del gastrónomoEduardo SaavedraRambla de Cataluña, 23Barcelona08022Spain
30Godos Cocina TípicaJosé Pedro FreyreC/ Romero, 33Sevilla41101Spain
39Königlich EssenPhilip CramerMaubelstr. 90Brandenburg14776Germany
44Lehmanns MarktstandRenate MessnerMagazinweg 7Frankfurt a.M.60528Germany
52Morgenstern GesundkostAlexander FeuerHeerstr. 22Leipzig04179Germany
56Ottilies KäseladenHenriette PfalzheimMehrheimerstr. 369Köln50739Germany
63QUICK-StopHorst KlossTaucherstraße 10Cunewalde01307Germany
69Romero y tomilloAlejandra CaminoGran Vía, 1Madrid28001Spain
79Toms SpezialitätenKarin JosephsLuisenstr. 48Münster44087Germany
86Die Wandernde KuhRita MüllerAdenauerallee 900Stuttgart70563Germany

Multi-Table INNER JOIN Queries

  • Table: Movies
IdTitleDirectorYearLength_minutes
1Toy StoryJohn Lasseter199581
2A Bug’s LifeJohn Lasseter199895
3Toy Story 2John Lasseter199993
4Monsters, Inc.Pete Docter200192
5Finding NemoAndrew Stanton2003107
6The IncrediblesBrad Bird2004116
7CarsJohn Lasseter2006117
8RatatouilleBrad Bird2007115
9WALL-EAndrew Stanton2008104
10UpPete Docter2009101
11Toy Story 3Lee Unkrich2010103
12Cars 2John Lasseter2011120
13BraveBrenda Chapman2012102
14Monsters UniversityDan Scanlon2013110
  • Table: Box-office
Movie_idRatingDomestic_salesInternational_sales
58.2380843261555900000
147.4268492764475066843
88206445654417277164
126.4191452396368400000
37.9245852179239163000
68261441092370001000
98.5223808164297503696
118.4415004880648167031
18.3191796233170162503
77.2244082982217900167
108.3293004164438338580
48.1289916256272900000
27.2162798565200600000
137.2237283207301700000
  • Find the domestic and international sales for each movie
SELECT title, domestic_sales, international_sales 
FROM movies
  JOIN boxoffice
    ON movies.id = boxoffice.movie_id;
TitleDomestic_salesInternational_sales
Finding Nemo380843261555900000
Monsters University268492764475066843
Ratatouille206445654417277164
Cars 2191452396368400000
Toy Story 2245852179239163000
The Incredibles261441092370001000
WALL-E223808164297503696
Toy Story 3415004880648167031
Toy Story191796233170162503
Cars244082982217900167
Up293004164438338580
Monsters, Inc.289916256272900000
A Bug’s Life162798565200600000
Brave237283207301700000
  • Show the sales numbers for each movie that did better internationally rather than domestically 
SELECT title, domestic_sales, international_sales
FROM movies
  JOIN boxoffice
    ON movies.id = boxoffice.movie_id
WHERE international_sales > domestic_sales;
TitleDomestic_salesInternational_sales
Finding Nemo380843261555900000
Monsters University268492764475066843
Ratatouille206445654417277164
Cars 2191452396368400000
The Incredibles261441092370001000
WALL-E223808164297503696
Toy Story 3415004880648167031
Up293004164438338580
A Bug’s Life162798565200600000
Brave237283207301700000
  • List all the movies by their ratings in descending order
SELECT title, rating
FROM movies
  JOIN boxoffice
    ON movies.id = boxoffice.movie_id
ORDER BY rating DESC;
TitleRating
WALL-E8.5
Toy Story 38.4
Toy Story8.3
Up8.3
Finding Nemo8.2
Monsters, Inc.8.1
Ratatouille8
The Incredibles8
Toy Story 27.9
Monsters University7.4
Cars7.2
A Bug’s Life7.2
Brave7.2
Cars 26.4

Multi-Table OUTER JOIN Queries

  • Table Buildings
Building_nameCapacity
1e24
1w32
2e16
2w20
  • Table Employees
RoleNameBuildingYears_employed
EngineerBecky A.1e4
EngineerDan B.1e2
EngineerSharon F.1e6
EngineerDan M.1e4
EngineerMalcom S.1e1
ArtistTylar S.2w2
ArtistSherman D.2w8
ArtistJakob J.2w6
ArtistLillia A.2w7
ArtistBrandon J.2w7
ManagerScott K.1e9
ManagerShirlee M.1e3
ManagerDaria O.2w6
  • Find the list of all buildings that have employees
SELECT DISTINCT building FROM employees;
Building
1e
2w
  • Find the list of all buildings and their capacity
SELECT * FROM buildings;
Building_nameCapacity
1e24
1w32
2e16
2w20
  • List all buildings and the distinct employee roles in each building (including empty buildings) 
SELECT DISTINCT building_name, role 
FROM buildings 
  LEFT JOIN employees
    ON building_name = building;
Building_nameRole
1eEngineer
1eManager
1w
2e
2wArtist
2wManager

SQL Queries with Expressions

  • We are going to have to use expressions to transform the Box Office table into something easier
  • Input data

Table Movies

IdTitleDirectorYearLength_minutes
1Toy StoryJohn Lasseter199581
2A Bug’s LifeJohn Lasseter199895
3Toy Story 2John Lasseter199993
4Monsters, Inc.Pete Docter200192
5Finding NemoAndrew Stanton2003107
6The IncrediblesBrad Bird2004116
7CarsJohn Lasseter2006117
8RatatouilleBrad Bird2007115
9WALL-EAndrew Stanton2008104
10UpPete Docter2009101
11Toy Story 3Lee Unkrich2010103
12Cars 2John Lasseter2011120
13BraveBrenda Chapman2012102
14Monsters UniversityDan Scanlon2013110

Table Box Office

Movie_idRatingDomestic_salesInternational_sales
58.2380843261555900000
147.4268492764475066843
88206445654417277164
126.4191452396368400000
37.9245852179239163000
68261441092370001000
98.5223808164297503696
118.4415004880648167031
18.3191796233170162503
77.2244082982217900167
108.3293004164438338580
48.1289916256272900000
27.2162798565200600000
137.2237283207301700000
  • List all movies and their combined sales in millions of dollars
SELECT title, (domestic_sales + international_sales) / 1000000 AS gross_sales_millions
FROM movies
  JOIN boxoffice
    ON movies.id = boxoffice.movie_id;

Query Results:

TitleGross_sales_millions
Finding Nemo936.743261
Monsters University743.559607
Ratatouille623.722818
Cars 2559.852396
Toy Story 2485.015179
The Incredibles631.442092
WALL-E521.31186
Toy Story 31063.171911
Toy Story361.958736
Cars461.983149
Up731.342744
Monsters, Inc.562.816256
A Bug’s Life363.398565
Brave538.983207
  • List all movies and their ratings in percent
SELECT title, rating * 10 AS rating_percent
FROM movies
  JOIN boxoffice
    ON movies.id = boxoffice.movie_id;

Query Results

TitleRating_percent
Finding Nemo82
Monsters University74
Ratatouille80
Cars 264
Toy Story 279
The Incredibles80
WALL-E85
Toy Story 384
Toy Story83
Cars72
Up83
Monsters, Inc.81
A Bug’s Life72
Brave72
  • List all movies that were released on even number years
SELECT title, year
FROM movies
WHERE year % 2 = 0;

Query Results

TitleYear
A Bug’s Life1998
The Incredibles2004
Cars2006
WALL-E2008
Toy Story 32010
Brave2012

SQL Queries with Aggregates

RoleNameBuildingYears_employed
EngineerBecky A.1e4
EngineerDan B.1e2
EngineerSharon F.1e6
EngineerDan M.1e4
EngineerMalcom S.1e1
ArtistTylar S.2w2
ArtistSherman D.2w8
ArtistJakob J.2w6
ArtistLillia A.2w7
ArtistBrandon J.2w7
ManagerScott K.1e9
ManagerShirlee M.1e3
ManagerDaria O.2w6
  • Find the longest time that an employee has been at the studio
SELECT MAX(years_employed) as Max_years_employed
FROM employees;

Output:

Max_years_employed
9
  • For each role, find the average number of years employed by employees in that role
SELECT role, AVG(years_employed) as Average_years_employed
FROM employees
GROUP BY role;

Output:

RoleAverage_years_employed
Artist6
Engineer3.4
Manager6
  • Find the total number of employee years worked in each building
SELECT building, SUM(years_employed) as Total_years_employed
FROM employees
GROUP BY building;
BuildingTotal_years_employed
1e29
2w36

Read more here.

SQL Cheat Sheets

CommandSyntaxDescription
SELECTSELECT column, another column, …
FROM mytable;
The result of this query will be a two-dimensional set of rows and columns, effectively a copy of the table, but only with the columns that we requested.
WHERESELECT column, another_column, … FROM mytable WHERE condition AND/OR another_condition AND/OR …;The clause is applied to each row of data by checking specific column values to determine whether it should be included in the results or not.
DISTINCTSELECT DISTINCT column, another_column, … FROM mytable WHERE condition(s);The clause provides a convenient way to discard rows that have a duplicate column value
ORDER BYSELECT column, another_column, … FROM mytable WHERE condition(s) ORDER BY column ASC/DESC;The clause provides a way to sort your results by a given column in ascending or descending order 
LIMIT and OFFSETSELECT column, another_column, …
FROM mytable
WHERE condition(s)
ORDER BY column ASC/DESC
LIMIT num_limit OFFSET num_offset;
The LIMIT will reduce the number of rows to return, and the optional OFFSET will specify where to begin counting the number rows from.
INNER JOINSELECT column, another_table_column, … FROM mytable INNER JOIN another_table ON mytable.id = another_table.id WHERE condition(s) ORDER BY column, … ASC/DESC LIMIT num_limit OFFSET num_offset;The INNER JOIN is a process that matches rows from the first table and the second table which have the same key (as defined by the ON constraint) to create a result row with the combined columns from both tables.
OUTER JOINsSELECT column, another_column, … FROM mytable INNER/LEFT/RIGHT/FULL JOIN another_table ON mytable.id = another_table.matching_id
WHERE condition(s) ORDER BY column, … ASC/DESC LIMIT num_limit OFFSET num_offset;
When joining table A to table B, a LEFT JOIN simply includes rows from A regardless of whether a matching row is found in B. The RIGHT JOIN is the same, but reversed, keeping rows in B regardless of whether a match is found in A. Finally, a FULL JOIN simply means that rows from both tables are kept, regardless of whether a matching row exists in the other table.
NULLSELECT column, another_column, … FROM mytable WHERE column IS/IS NOT NULL AND/OR another_condition AND/OR …;If your database needs to store incomplete data, then NULL values can be appropriate, especially when the default values will skew later analysis.
Queries with expressionsSELECT col_expression AS expr_description, … FROM mytable;Use them in the SELECT part of the query, and give them descriptive alias using the AS keyword.
Queries with aggregates SELECT AGG_FUNC(column_or_expression) AS aggregate_description, … FROM mytable WHERE constraint_expression GROUP BY column;SQL also supports the use of aggregate expressions (or functions) that allow you to summarize information about a group of rows of data. 

Read more here.

Interview Q&A

QuestionAnswer
What are the five basic SQL commands?ALTER, UPDATE, DELETE, INSERT, and CREATE
How are SQL commands classified?Data Definition Language (DDL)
Data Manipulation Language (DML)
Data Control Language (DCL)
Transaction Control Language (TCL)
Data Query Language (DQL)
How do you create/delete a table in SQL?CREATE TABLE
DROP TABLE
What are constraints in SQL?Constraints are the rules that are set for the data that can be placed inside a table:
NOT NULL: The data in this column cannot include any null values. 
UNIQUE: Every entry in this column needs to be unique. 
PRIMARY KEY: These are columns that have data that are unique for each record in the column. 
CHECK: This constraint checks every entry in a column for a specific condition. 
FOREIGN KEY: These are columns with attributes that refer to the primary key of a different table. 
DEFAULT: This constraint sets a default value for when no value is entered. 
CREATE INDEX: This is used to create indexes in tables so that data can be retrieved quickly. 
How do you change a table name in SQL?RENAME old new
How do you delete a row in SQL?DELETE FROM Cars WHERE sno=6
How do you create a database in SQL?CREATE DATABASE StudentInfo
Define an index, along with its different typesAn index is a table that has two columns. The first column is a duplicate of the primary key of a table. The second column has pointers to where the key value of each record is stored. 
Primary index (dense index and sparse index)
Secondary index
Clustering index 
Multi-level index
B-tree index 
What is PL/SQL?PL/SQL is short for Procedural Language Extensions to the Structured Query Language. It gives software developers a way to combine SQL with procedural statements like the ones used in general-purpose programming languages. 
What is MySQL?MySQL is an open-source relational database management system software. It was created by Oracle and based on SQL. 
What are the different types of relationships in SQL?There are three main types of relationships between data values in SQL. They are: 
One-to-one relationship: This implies that a record in the first table is related to only one record in the second table. 
One-to-many relationship: In a one-to-many relationship, a record in the first table can be related to one or more records in the second table. But the records in the second table can be related only to one record in the first table. 
Many-to-many relationship: In this kind of relationship, multiple records in the first table are related to multiple records in the second table. 
What is a schema in SQL?A schema is a logical representation of the different objects in the database. Think of it as a mapping of all the tables, functions, stored procedures, and indexes that are part of a database.
Discuss standard clauses used with SELECT query in SQL?WHERE: Used to select items based on a specific set of conditions 
GROUP BY: Used to group rows whose values match that of the result set
ORDER BY: Arranges the resulting set in descending or ascending order
TOP: Sets a limit on the number of records returned by a query
HAVING: Serves the same function as the WHERE clause except that it can be used with aggregate functions 
Explain UNION, MINUS, and INTERSECT commands. The UNION command combines the output of two select queries into a single result.
INTERSECT is also a binary set operator like the UNION command, except that it outputs the rows that are in common between the results of two SELECT queries.
The MINUS command is the opposite of the INTERSECT command. When you apply MINUS to the results of two SELECT queries, it returns the rows that are in the first selection but not in the second one. 
What is a “view” in SQL?A view is a table that holds data from one or multiple tables in an SQL database, but doesn’t actually physically exist in the memory.
How to use BETWEEN in SQL?The BETWEEN statement in SQL is used to select values that fall within a particular range. These values can be text, numbers, or dates. 
What is the difference between an inner join and an outer join?An inner join focuses on the data that two tables have in common. It is essentially the intersection of the two datasets. 
An outer join also includes the data that two tables have in common. But along with that, it also returns rows for which there is no match in the other table. 
What is the difference between B-Tree and hash indexing in SQL?Balanced trees, or B-trees, are used to make comparisons between columns that use the =, >, >=, <, <= operators or the BETWEEN clause. Hash indexes are used for comparisons using only the operators = or ⇔. 
What is the difference between UNION and UNION ALL?The difference between the UNION and UNION ALL commands lies in the way they treat duplicate records. 
When you use the UNION command, it combines the data in two tables, but also eliminates duplicate data. UNION ALL doesn’t remove duplicate values and combines all of the data in the two tables. 
How and when do you use the GROUP BY function?The GROUP BY command quite simply groups rows in a table that have the same values. 
What are the most common aggregate functions in SQL?COUNT – Counts the number of rows in a specific table or a view
AVG – Calculates the average value from a given set of values
MAX – Identifies the maximum value in a given set of values 
MIN – Identifies the minimum value in a given set of values
SUM – Outputs the sum of a given set of values
How do you copy a table in SQL?SELECT * INTO T2 FROM T1;
What is the SQL Injection?SQL injection is a code injection technique that might destroy your database.
SQL injection is one of the most common web hacking techniques.
SQL injection is the placement of malicious code in SQL statements, via web page input.
What are SQL editors?With online SQL editors, you can edit SQL statements, and view the result in your browser.
What is PostgreSQL?PostgreSQL is an open-source relational database system with advanced features for enterprise use cases. It offers support for most of the popular programming languages, including Python, C, Javascript, Java, and Ruby. 
What is a trigger in SQL?A trigger is a specialized procedure in SQL which runs automatically when a particular event occurs or a certain condition has been met. 
What are the differences between SQL and Transact Structured Query Language (TSQL)?SQL was developed by IBM whereas TSQL was developed by Microsoft. 
SQL is used to execute one query at a time to insert, update, or delete the data in a database. TSQL makes it possible to carry out transactional activities in a database using various programmatic techniques. 
SQL is focused on manipulating the data in a database. TSQL is used to build applications and implement business logic within them. 
What are the differences between MongoDB and SQL?SQL databases are relational in nature whereas MongoDB has non-relational databases. 
SQL uses the commands and statements in the SQL query language. MongoDB uses JSON as its query language. 
SQL is vertically scalable, whereas MongoDB is horizontally scalable. 
SQL focuses on the properties of ACID: atomicity, consistency, isolation, and durability. MongoDB emphasizes CAP properties: consistency, availability, and partition tolerance. 
What are the differences between NoSQL and SQL?SQL is a database management software that supports the storage and analysis of structured data. NoSQL allows you to store and retrieve structured data but also offers support for unstructured and polymorphic data. 
SQL was created in the year 1970 to deal with problems relating to file storage. NoSQL came about in the early 2000s as a way to allow databases to handle semi-structured and unstructured data. 
SQL is vertically scalable, which means that you can add resources so that the existing hardware and software can handle greater capacities. NoSQL is horizontally scalable and lets you add larger nodes to smaller nodes to enhance its capacity. 
There is no support for storing data hierarchically in SQL whereas NoSQL is especially suited to handling hierarchical data. 
SQL doesn’t support the distribution of data, which means that one installation can only run on one system. Features like partition and repetition mean that NoSQL allows data distribution. 

Read more here.

Discussion

  • Let’s discuss SQL using Python, viz. integrating SQLite3 with Python
  • To use SQLite, we must import sqlite3
  • Then create a connection using connect() method and pass the name of the database
  • After this, a cursor object is called to be capable to send commands to the SQL
  • Output: Connected to the database
  • To execute a query in the database, create an object and write the SQL command in it with being commented. Example:- sql_comm = ”SQL statement”
  • Execute the command: call the cursor method execute() and pass the name of the sql command as a parameter in it.

Conclusions

  • SQL (Structured Query Language) is a language to operate databases
  • SQL is an ANSI/ISO certified standard and mostly all the RDMS like MySQL, MS Access, Oracle, Sybase, Informix, PostgreSQL and SQL Server use SQL as a standard database query language
  • SQL is a medium to communicate with the data stored in the relational database. It can perform all the CRUD (CREATE, RETRIEVE, UPDATE, DELETE) operations in the database
  • SQL is used by most of the database programs present. (i.e. SQL Server, MYSQL, SQLite, etc.)
  • SQL is widely popular because it offers the following advantages:
  • Allows users to access data in the relational database management systems.
  • Allows users to describe the data.
  • Allows users to define the data in a database and manipulate that data.
  • Allows to embed within other languages using SQL modules, libraries & pre-compilers.
  • Allows users to create and drop databases and tables.
  • Allows users to create view, stored procedure, functions in a database.
  • Allows users to set permissions on tables, procedures and views.

The Road Ahead

10 Advanced SQL Concepts You Should Know for Data Science Interviews:

  • Common table expressions (CTEs).
  • Recursive CTEs.
  • Temporary functions.
  • Pivoting data with case when.
  • Except versus Not In.
  • Self joins.
  • Rank versus dense rank versus row number.
  • Calculating delta values.
  • Calculating running totals.
  • Date-time manipulation.

Resources


Go back

Your message has been sent

Warning

One-Time
Monthly
Yearly

Make a one-time donation

Make a monthly donation

Make a yearly donation

Choose an amount

€5.00
€15.00
€100.00
€5.00
€15.00
€100.00
€5.00
€15.00
€100.00

Or enter a custom amount


Your contribution is appreciated.

Your contribution is appreciated.

Your contribution is appreciated.

DonateDonate monthlyDonate yearly

Discover more from Our Blogs

Subscribe to get the latest posts sent to your email.

Leave a comment

Discover more from Our Blogs

Subscribe now to keep reading and get access to the full archive.

Continue reading