According to the Bureau of Labor Statistics, the job outlook for computer and information research scientists, data scientists is projected to grow by at least 19 per cent by 2026. Data is collected and processed in every company regardless of the domain.
Data scientists dive into the data to find valuable insights beneficial to the company.
Why learn SQL?
Most companies store and manage their data with Relational Database Management System (RDBMS).
SQL stands for Structured Query Language, and it lets users access and manipulate the data. Companies use different systems like MySQL, PostgreSQL, Oracle database, etc., for data storage. There are slight differences between all these different versions of SQL, but shifting to the other is relatively easy once you get hold of one performance.
I’ll be using Oracle Live SQL in this article, but you can try it out on any other version as well. In case of any error, you can google to find out solutions.
Data Scientists deal with already maintained databases, but we will start from the basics.
What is a Database Table in SQL?
Data in databases is stored in tables that can be thought of, just like Excel spreadsheets. Each spreadsheet has rows and columns. Each row consists of data related to an entity (like a person, company, etc.) & each column consists of data concerning a specific aspect of the row (like name, account_id, age, etc.)
In the above table, each row contains information about a single employee & each column denotes specific feature information of the employee.
SQL Naming Convention
Note that SQL is not case-sensitive. It treats “table” the same as “TABLE”. But it is conventional to write SQL commands in all capitals, Database tables are named in lower letters and underscores are used instead of spaces.
Create Tables
The syntax for creating new tables in SQL is as below.
We use CREATE TABLE statement followed by the table name. Then we mention column names along with their datatype inside parentheses. Note that every SQL statement ends with a semicolon.
Some of the widely used data types in SQL are VARCHAR(string), BOOL (boolean), int(integer), FLOAT(floating numbers), DATETIME(DateTime), etc. You can refer to the documentation to learn more about data types.
Let’s create a new table, as shown in the image above.
Now let’s insert dummy values into the table we created above.
INSERT INTO employee VALUES (1,'Alex',27,28000,'Designer');
INSERT INTO employee VALUES (2,'Joe',30,45000,'Backend Dev');
INSERT INTO employee VALUES (3,'Rick',25,65000,'Data Scientist');
INSERT INTO employee VALUES (4,'Nick',21,30000,'Backend Dev');
INSERT INTO employee VALUES (5,'Cathy',21,35000,'Designer');
We can view our table data using the SELECT statement, which we will look at next. Mini Task: Add five employees more to the table (make sure the employee_id is unique).
SELECT & FROM
The SELECT statement is used to select data from a database. The FROM statement lists out the database table we will be taking data from.
SELECT column_name_1,column_name_2, . . .
FROM table_name;
To select all columns in the database column, replace the column names with an asterisk (*).
We will now view all employee dataset columns using the below statement.
SELECT * FROM employee;
Output in Oracle Live SQL
Mini Task: Display Names of all Employees
So right now, we can display the contents of the database table without filtering. But what if we want to show names of employees who have a salary of more than 50,000 PokeDollars (yes, you’ve read it right). Here are various statements like WHERE, LIKE, IN, etc.
We will focus on such statements now.
WHERE
WHERE statement filters out records based on the condition mentioned after the statement, the syntax is as below.
SELECT column1,column2, . . .
FROM table_name
WHERE condition;
Code to filter out employees having salaries of more than 50,000 PokeDollars is as below.
SELECT *
FROM employee
WHERE salary>50000;
Note that the WHERE statement is placed below FROM statement.
Inside the condition, we can use logical expressions (OR, AND & NOT) as well as comparison operators like >, <, =, = (in SQL, we use = instead of == for equality comparison), etc.
We can also use particular expressions like IN, BETWEEN, LIKE, etc.
AND, OR & NOT
These three are some of the most commonly used logical operators. I believe these operators don’t need any explanation, so here’s a table containing example conditions.
LIKE
Before explaining the LIKE operator, let’s say we want to filter out the Backend developers working in our company. You may use the WHERE statement and comparison operator as below.
SELECT *
FROM employee
WHERE job='Backend Developer';
The problem with this kind of query is, as you can see in our database table, there is another backend developer (Nick) in our table who didn’t get filtered as his job title is ‘Backend Dev’. So to get through this problem, we will use the LIKE operator.
So we can find Backend Developers using the below query.
SELECT *
FROM employee
WHERE job LIKE '%Backend%';
% character represents zero, one, or multiple characters.
Mini Task: Find employees whose name starts with a vowel (Hint: You need to use multiple OR operators).
There’s a catch here, lower and upper case letters are not the same in a string. Searching for the word “Backend” will miss out on all instances with “backend” in the job title.
So to get rid of this flaw, we need to temporarily convert the string to Upper or Lowercase & then compare it.
For example, the modified query will be
SELECT *
FROM employee
WHERE UPPER(job) LIKE '%BACKEND%';
BETWEEN
We want to find all employees having salaries between 25,000 and 40,000 (inclusive). We can do it using AND and comparison operators as below.
SELECT *
FROM employee
WHERE salary>=25000 AND salary<=40000;
Another way of doing this is with the help of BETWEEN Operator. The BETWEEN operator is inclusive: begin and end values are included.
We can perform the above query using BETWEEN Operator.
SELECT *
FROM employee
WHERE salary BETWEEN 25000 AND 40000;
Mini Task: Filter out all employees having salaries between 30,000 and 40,000 (exclusive).
IN
Here we explicitly define a list of values and return the records containing any of the values from the list. We want to select employees with employee_id either 1, 3, or 5.
SELECT *
FROM employee
WHERE employee_id IN (1,3,5);
This is similar to having multiple conditions linked together using an OR statement (WHERE employee_id=1 OR employee_id=3 . . .) Mini Task: Select all employee names with employee_id 2 and 5.
LIMIT/FETCH
Okay, now enough of filtering out based on some conditions. What if we want to select only the top 3 employees of the table. We can quickly achieve this by using the LIMIT keyword, and it is placed at the end of the query code. Just enter LIMIT and the count of records we want to show & we are done.
Note: Remember we talked briefly about different versions of SQL and how there can be slight differences in the syntax. We need to use “FETCH FIRST number ROWS ONLY” instead of “LIMIT number” in Oracle SQL. Refer to SQL version documentation for more information.
Let’s show the top 2 records of the table.
SELECT *
FROM employee
FETCH FIRST 2 ROWS ONLY;
ORDER BY
As the name suggests, the ORDER BY statement sorts the result in Ascending or Descending order.
The column (or columns) by which the results should be sorted is added after the ORDER BY keyword.
It sorts the results in ascending order by default. To sort it by descending order, we need to add DESC at the end of the ORDER BY statement.
Let’s say we want to display the top 3 most-earning employees. The code will be as below.
SELECT *
FROM employee
ORDER BY salary DESC
FETCH FIRST 3 ROWS ONLY;
Mini Task: Select the top 3 youngest employees.
Conclusion on SQL
So that’s it for the basics. I’ll highly suggest you try solving SQL Basic Select coding questions on Hackerrank.
This is not the end, as SQL consists of more complex topics like Joins, Window functions, etc. Nevertheless, this is a step in the right direction.
Sources
I created all of the images shown in the article (author).
The media shown in this article is not owned by Analytics Vidhya and are used at the Author’s discretion.
I'm an Engineering student, Mobile Dev Head at GDSC RAIT and an avid Data Science Enthusiast. I love to document everything I learn and thus I'm a technical writer as well. Technical writing helps me question my in-depth knowledge about any topic.
We use cookies essential for this site to function well. Please click to help us improve its usefulness with additional cookies. Learn about our use of cookies in our Privacy Policy & Cookies Policy.
Show details
Powered By
Cookies
This site uses cookies to ensure that you get the best experience possible. To learn more about how we use cookies, please refer to our Privacy Policy & Cookies Policy.
brahmaid
It is needed for personalizing the website.
csrftoken
This cookie is used to prevent Cross-site request forgery (often abbreviated as CSRF) attacks of the website
Identityid
Preserves the login/logout state of users across the whole site.
sessionid
Preserves users' states across page requests.
g_state
Google One-Tap login adds this g_state cookie to set the user status on how they interact with the One-Tap modal.
MUID
Used by Microsoft Clarity, to store and track visits across websites.
_clck
Used by Microsoft Clarity, Persists the Clarity User ID and preferences, unique to that site, on the browser. This ensures that behavior in subsequent visits to the same site will be attributed to the same user ID.
_clsk
Used by Microsoft Clarity, Connects multiple page views by a user into a single Clarity session recording.
SRM_I
Collects user data is specifically adapted to the user or device. The user can also be followed outside of the loaded website, creating a picture of the visitor's behavior.
SM
Use to measure the use of the website for internal analytics
CLID
The cookie is set by embedded Microsoft Clarity scripts. The purpose of this cookie is for heatmap and session recording.
SRM_B
Collected user data is specifically adapted to the user or device. The user can also be followed outside of the loaded website, creating a picture of the visitor's behavior.
_gid
This cookie is installed by Google Analytics. The cookie is used to store information of how visitors use a website and helps in creating an analytics report of how the website is doing. The data collected includes the number of visitors, the source where they have come from, and the pages visited in an anonymous form.
_ga_#
Used by Google Analytics, to store and count pageviews.
_gat_#
Used by Google Analytics to collect data on the number of times a user has visited the website as well as dates for the first and most recent visit.
collect
Used to send data to Google Analytics about the visitor's device and behavior. Tracks the visitor across devices and marketing channels.
AEC
cookies ensure that requests within a browsing session are made by the user, and not by other sites.
G_ENABLED_IDPS
use the cookie when customers want to make a referral from their gmail contacts; it helps auth the gmail account.
test_cookie
This cookie is set by DoubleClick (which is owned by Google) to determine if the website visitor's browser supports cookies.
_we_us
this is used to send push notification using webengage.
WebKlipperAuth
used by webenage to track auth of webenagage.
ln_or
Linkedin sets this cookie to registers statistical data on users' behavior on the website for internal analytics.
JSESSIONID
Use to maintain an anonymous user session by the server.
li_rm
Used as part of the LinkedIn Remember Me feature and is set when a user clicks Remember Me on the device to make it easier for him or her to sign in to that device.
AnalyticsSyncHistory
Used to store information about the time a sync with the lms_analytics cookie took place for users in the Designated Countries.
lms_analytics
Used to store information about the time a sync with the AnalyticsSyncHistory cookie took place for users in the Designated Countries.
liap
Cookie used for Sign-in with Linkedin and/or to allow for the Linkedin follow feature.
visit
allow for the Linkedin follow feature.
li_at
often used to identify you, including your name, interests, and previous activity.
s_plt
Tracks the time that the previous page took to load
lang
Used to remember a user's language setting to ensure LinkedIn.com displays in the language selected by the user in their settings
s_tp
Tracks percent of page viewed
AMCV_14215E3D5995C57C0A495C55%40AdobeOrg
Indicates the start of a session for Adobe Experience Cloud
s_pltp
Provides page name value (URL) for use by Adobe Analytics
s_tslv
Used to retain and fetch time since last visit in Adobe Analytics
li_theme
Remembers a user's display preference/theme setting
li_theme_set
Remembers which users have updated their display / theme preferences
We do not use cookies of this type.
_gcl_au
Used by Google Adsense, to store and track conversions.
SID
Save certain preferences, for example the number of search results per page or activation of the SafeSearch Filter. Adjusts the ads that appear in Google Search.
SAPISID
Save certain preferences, for example the number of search results per page or activation of the SafeSearch Filter. Adjusts the ads that appear in Google Search.
__Secure-#
Save certain preferences, for example the number of search results per page or activation of the SafeSearch Filter. Adjusts the ads that appear in Google Search.
APISID
Save certain preferences, for example the number of search results per page or activation of the SafeSearch Filter. Adjusts the ads that appear in Google Search.
SSID
Save certain preferences, for example the number of search results per page or activation of the SafeSearch Filter. Adjusts the ads that appear in Google Search.
HSID
Save certain preferences, for example the number of search results per page or activation of the SafeSearch Filter. Adjusts the ads that appear in Google Search.
DV
These cookies are used for the purpose of targeted advertising.
NID
These cookies are used for the purpose of targeted advertising.
1P_JAR
These cookies are used to gather website statistics, and track conversion rates.
OTZ
Aggregate analysis of website visitors
_fbp
This cookie is set by Facebook to deliver advertisements when they are on Facebook or a digital platform powered by Facebook advertising after visiting this website.
fr
Contains a unique browser and user ID, used for targeted advertising.
bscookie
Used by LinkedIn to track the use of embedded services.
lidc
Used by LinkedIn for tracking the use of embedded services.
bcookie
Used by LinkedIn to track the use of embedded services.
aam_uuid
Use these cookies to assign a unique ID when users visit a website.
UserMatchHistory
These cookies are set by LinkedIn for advertising purposes, including: tracking visitors so that more relevant ads can be presented, allowing users to use the 'Apply with LinkedIn' or the 'Sign-in with LinkedIn' functions, collecting information about how visitors use the site, etc.
li_sugr
Used to make a probabilistic match of a user's identity outside the Designated Countries
MR
Used to collect information for analytics purposes.
ANONCHK
Used to store session ID for a users session to ensure that clicks from adverts on the Bing search engine are verified for reporting purposes and for personalisation
We do not use cookies of this type.
Cookie declaration last updated on 24/03/2023 by Analytics Vidhya.
Cookies are small text files that can be used by websites to make a user's experience more efficient. The law states that we can store cookies on your device if they are strictly necessary for the operation of this site. For all other types of cookies, we need your permission. This site uses different types of cookies. Some cookies are placed by third-party services that appear on our pages. Learn more about who we are, how you can contact us, and how we process personal data in our Privacy Policy.