How to write a query in SQL

In this article we will learn about database query, SQL commands and its types.

Database Query:

Database Query is a request for data from a database. Usually, the request is to retrieve or manipulate data in a database. In simple words query is a question. It is similar to performing some sort of CRUD (Create, Read, Update, Delete) operations. A number of database query languages are available and one such query language is SQL. It is designed for relational database and displays results in the form of rows and columns.

SQL commands:

SQL commands are instructions used to perform operations such as

  • Create and drop database and tables
  • Retrieve information from tables and database
  • Create a view, stored procedure and functions in a database
  • Set permissions for users
  • Add data to database
  • Modify database

Types of SQL commands:

SQL commands are differentiated based on their functionality as

  • DDL (Data Definition Language)
  • DML (Data Manipulation Language
  • DCL (Data Control Language)
  • TCL (Transaction Control Language)
  • DQL (Data Query Language)

DDL :

Data Definition Language consists of commands that can be used to define the database schema and deals with its description. It changes the structure of the table like creating, deleting or altering etc.,

All DDL commands are auto-commited which means changes are permanently saved in the database.

Create

It is used to create a database and its objects like tables, views, procedures.

Syntax

CREATE DATABASE database_name;

CREATE TABLE table_name( column name datatypes[,…]);

CREATE PROCEDURE procedure_name

AS

sql statement logic

GO;

Example

CREATE TABLE Employee(Name varchar(20), Age int(3),Id int(3));

Drop

The Drop is used to delete the existing database objects in a database.

Syntax

DROP TABLE table_name;

DROP DATABASE database_name;

DROP PROCEDURE procedure_name;

Example

DROP TABLE Employee;

Alter

This is used to change the structure of the database. It modifies the existing records in a database.

Syntax

ALTER TABLE table_name ADD column_name column_definition;

Example

ALTER TABLE Employee ADD City varchar(50);

Truncate

Truncate is used to delete all data from the table except for the database schema(structure).

Syntax

TRUNCATE TABLE table_name;

Example

TRUNCATE TABLE Employee;

Rename

Rename is used to rename table existing in the database. SQL server does not have any statement that directly renames a table but it has a stored procedure sp_rename which allows to change the name of the table.

Syntax

EXEC sp_rename ‘old_table_name’, ‘new_table_name’;

Example

EXEC sp_rename ‘Employee’, ‘Employee_details’;

Comment

It is used to add comments to the data dictionary.

There are two types of comments in SQL

  • Single-line comments starts with double hypens (- -).
  • Multi-Line comments starts with /* and ends with */.

DML

DML stands for Data Manipulation Language. These commands are used to modify the database. It is responsible for all form of changes in the database. DML commands include insert, update, delete, merge, call, explain plan, lock table.

If we enter wrong information in a table, we can easily modify the table by changing and roll backing it. There are two types of DML

  • Procedural: The user specifies what data is needed and how to get that data. E.g.: Relational Algebra.
  • Non-Procedural (Declarative): In this method only what data is needed is specified. It is easier for user but this is not as efficient as Procedural languages. E.g.: Tuple Relational Calculus.
Insert:

Insert command is used to insert new records or new rows in a database table.

               Syntax:

                              INSERT INTO table_name(colum1, column2,…) VALUES(value1,value2,…)

               Example:                INSERT INTO Employee (Id, Name) VALUES ( 1001, “John” );
Update:

Update is used to update or modify existing data in the table. Using Update we can modify single column or multiple columns at the same time.

               Syntax:

                              UPDATE table_name SET col1 = value1, col2=value2,…colN=valueN WHERE condition;

               Example:

                              UPDATE Employee SET salary = 10000 WHERE Id = 1001; (Modify Single Column)

                              UPDATE Employee SET salary = 10000, Name = “John” WHERE Id=1001; (Modify Multiple Columns)

WHERE clause in UPDATE command is optional. If we omit WHERE clause then salary = 10000 will be updated for all employees.

Delete:

Delete is used to delete records or entire table. It can be used with WHERE clause.

               Syntax:

                              DELETE FROM table_name WHERE condition;

               Example:

                              DELETE FROM Employee WHERE Id = 1001; (single record deleted)

DELETE FROM Employee WHERE salary=15000; (multiple record deleted)

                              DELETE FROM Employee; ( all records of the table deleted)

Merge:

Merge is used to UPSERT (Update and Insert) operations. It merges the two rows of existing tables in a database.

Call:      

It is used to call PL/SQL or Java Subprogram.

Lock Table:

It is used for concurrency control. It locks the privileges as either read or write.

Example:

               LOCK TABLE Employee read.

Explain Plan:

It is used for the interpretation of data access path.

DQL:

It is also known as Data Query Language. Purpose is to get some schema relation based on the query passed to it. It has only one command.

SELECT:

               SELECT command is used in combination with other SQL clauses to fetch data from database or table based on certain conditions.

Syntax:

               SELECT *FROM table_name;

               SELECT col1,col2…colN FROM table_name;

Example:

               SELECT *FROM Employee;

               SELECT Id, Name FROM Employee;

DCL:

This is Data Control Language (DCL). It allows users to retrieve and edit data held in database. It also allows us control access within the database. It controls the distribution of privileges among various users of the database. Privileges are of two types:

  • System: This includes permission of creating sessions, tables etc., and all other system privileges.
  • Object: This includes  permission for access to any command or query to perform any action on the database.

Command types are: GRANT and REVOKE.

GRANT:

               User access privileges are given by this command.

System Privileges:
               Syntax:

                              GRANT privilege_name TO user_name [WITH ADMIN OPTIONS];

               Example:

                              GRANT CREATE TABLE TO John;

                              Allows user John to create table.

                              GRANT CREATE TABLE TO John WITH ADMIN OPTIONS;

                              Allows user John to create table and assign the same privileges to other users.

Object Privileges:
               Syntax:

                              GRANT privilege_name ON object_name To {user_name | Public| role_name} [WITH ADMIN OPTIONS];

               Example:

                              GRANT SELECT ON Employee TO John;

                              This will grant Select Privilege on object Employee to user John.

                              GRANT SELECT ON Employee TO John WITH GRANT OPTIONS;

                              This will grant Select privilege on object Employee to user John and he can also grant this privilege to other users.

REVOKE:            

               It removes or take back certain privileges given to users.

               Syntax:

                              REVOKE privilege_name ON object_name TO user_name[CASCADE | RESTRICT];

                              [CASCADE | RESTRICT] clause is optional.

               Example:

                              REVOKE SELECT ON Employee FROM John;

TCL:

               TCL stands for Transaction Control Language. This deals with transactions within the database. It is used to handle DML modifications. This saves the state of the transaction.

COMMIT:

               This command saves all the transactions in the database.

Syntax:

               COMMIT;

Example:

               Update Employee SET salary = 15000 WHERE Id=1001;

               COMMIT;

ROLLBACK:

                              Rollback is used to undo transactions that have not already been saved in the database. This command can only be used since the last COMMIT or ROLLBACK is used. It restores the database to original state since the last COMMIT.

               Syntax:

                              ROLLBACK;

               Example:

                              DELETE FROM Employee WHERE Id=1001;

                              ROLLBACK;

               SAVEPOINT:

                              Savepoint is used to rollback the transaction to a certain point without rolling back the entire transaction.

               Syntax:

                              SAVEPOINT savepoint_name;

               Example:

                              SAVEPOINT s1;

                              DELETE FROM Employee WHERE Id=1001;

                              SAVEPOINT s2;

These are the SQL commands and its types that we see in a database.

Delete, Truncate and Drop Table in SQL

Let us understand the difference between delete truncate and drop table:

Delete Truncate and Drop Table:

CharacteristicsDeleteTruncateDrop
Command TypeDML(Data Manipulation Language)DDL(Data Definition Language)DDL(Data Definition Language)
Rollback transactionCan be rolled backCannot be rolled backCannot be rolled back
Permanent deleteSince it is DML does not remove records permanentlySince it is DDL removes the records permanentlySince it is DDL removes the records permanently
TriggerTrigger is firedNo trigger usedNo trigger used
PerformanceSlower than truncateFaster than deleteQuick but some complications
Can we use WHERE clause?Yes WHERE clause can be usedNo WHERE clause can be usedNo WHERE clause can be used
SyntaxDELETE FROM table_name;TRUNCATE table_name;DROP table_name;
UsageUsed to delete records in the tableUsed to delete data and keep the table schema as it isUsed to delete data as well as table structure.
Example:Delete from Employee where salary>25000;Truncate table Employee;Drop table Employee;

With the above mentioned tabular form difference we can easily understand the difference between delete, truncate and drop in SQL

Deep Insight into Big Data: Understanding Big Data Basics

What is Big Data?

Big data refers to the large collection of structured, semi-structured and unstructured data mostly collected from Internet connected devices. This represents the massive amount of data an organization is exposed to daily and cannot be managed by traditional database management systems. It led to the evolution of model-driven paradigm to data-driven paradigm. It is always important how an organization use this large data to yield insights that results in better informed decisions. The importance of big data is not in the amount of data but how you use this data.

Characteristics of Big Data

The term big data refers to large data set (Volume), structured, semi-structured and unstructured data (Variety), arriving faster than before (Velocity).  These are 3V.

3V:

Volume:       

            The volume of data stored today is growing exponentially and exploding. Now the data volume has grown from terabytes to zettabytes.

Velocity:

            Represents both the rate at which the data is generated and needs to be handled.

Variety:

            As data collected is not from a single source the variety of data also differs according to the source like emails, web, text or sensors by structured or unstructured data.

Now as big data evolved in due course of time the characteristics also evolved from 3Vs to 6Vs.

6V:

As data grows tremendously in todays internet world, today’s big data is tomorrow’s small data.   

How to serve food without any contact in Restaurant using Corona App

Objective:

The main purpose of the App is to provide food services at the restaurant with minimum contact. It also includes managing the customer service tables to ensure appropriate distance between two customers. The Food Service is digitalised with the menu options available through the App. The information of the customer is stored based on the customer preference. The customer feedbacks are analysed to improve the food service. The complete restaurant services can be administered centrally using the App.

Major features of the App:

  1. The Food service tables are digitalised.
  2. The Food menu options are controlled dynamically through the App.
  3. The data flow between the service tables and the kitchen service can be controlled through the App.
  4. The customer feedbacks and the sales are analysed using Lean Management Techniques.
  5. The critical customer information can be managed centrally with a client no with the consent of the customer.
  6. The pre-order options can be available based on the Restaurant needs.

Food Service Table:

The QR Bar code option can be used to uniquely identify the food service table. customer cannot enter any random no to book the Food Service Table.

Menu Options:

            The menu options should always be dynamic displayed on the current day options. In case if a food item is not available during a day, then it should automatically be hidden from the display. The special menu for the day can be highlighted.

Kitchen Service:

            The Kitchen Service is alerted centrally using a Display that is controlled by the main service pattern. The data flow between the customer and kitchen Service must be fast and transparent.

Customer Feedbacks:

            The customer orders and feedbacks are analysed daily, weekly, monthly. Lean principles must highlight the food with high revenue. It should also indicate peak service time during each day. The app must help in solving the customer feedbacks, on the next subsequent corresponding customer visit. The respective customer and the restaurant manger must be aware of the resolved issue.

Pre-order Option:

            The App gives an option to book the food service table in advance.

Critical points for the development of the App:

  1. The customer data can be stored as a client no in the server centrally. The actual customer data must always be stored locally with restaurant manager. This ensure that the customer data is protected to the maximum.
  2. The App, storage cost is estimated against the return on investment.
  3. The data flow between the different point, must be checked with parameters such as data size.
  4. The Food Menu options must always be dynamically controlled with less inputs from the App user (Restaurant manager).
  5. Secure payment options can be an additional feature.

Market Analysis:

The App is specifically suited for the local German markets for the following reasons:

  • Customer data being stored locally with the restaurant.
  • Current pandemic situation enforces less contact in public places such as restaurants. German locals wish to enjoy the Restaurant atmosphere rather than placing the order from home.
  • Simple to develop features such as QR barcode and local storage implementation
  • One real time case is Vapiano restaurant which had to close due to the loss incurred during the pandemic.
ParametersCurrent proposal
Book orders 
Customer reviews 
Payment service 
Local table control option 
Local data storage 
Tasks
User Interface, Database Architecture
Object model, Framework, Business logic
Testing
Implementation
Main elements for the development of the App

User Interface:

Restaurant Manager

Customer Display
Kitchen Display

Conclusion:

                        The App solves the current pandemic issue with less contact in the Restaurant. The Restaurant can be controlled centrally, and its sales can be monitored every hour. It is an affordable App to meet the local requirements of a restaurant and all the data are stored to only a confined network.

How Data and Analytics Are Driving Digital Business?

In this article, we will discuss how data and analytics are impacting business and in our day-to-day lives and how important in digital businesses and their applications in the real world.

In the past, organizations would use analytic applications mainly for enterprise data reporting. However, more and more organizations are now using data and analytics as raw materials for enterprise-level decision making. The following flowcharts illustrate this point:

Analytics allows for informed decisions.

The Current Al Wave Is Poised to Finally Break Through.

Al is becoming fast a core business and analytical competency. Al and ML technologies are providing rapidly improved decision making and process optimization capabilities to organizations.

By doing so, these technologies promise to:

  • Transform business processes.
  • Reconfigure workforces.
  • Optimize infrastructure behavior.
  • Blend industries.

Natural Language Technologies Become Mainstream.

One of the key aspects of Al-driven systems is their ability to process natural language, which is human
speech and text. Natural language is beginning to play a dual role in many organizations.

Examples of Natural Language Processing (NLP):

  • Machine Translation: Google translate services.
  • Customer Service: NLP is being used in customer service contact centers to understand customer intent, pain-points, and to provide enhanced customer satisfaction.

Examples of Natural Language Generation:

  • Generating automated product descriptions from inventory data.
  • Creating individual financial portfolio summaries and updates at scale.
  • Business intelligence performance dashboard text explanations
  • Automated personalized customer communications.

Augmented analytics draws on ML, AI, and natural language generation technologies to:


Applications in real world:

The combination of emerging technologies such as AI, ML, and cloud are often marketed using the following:
• Cognitive Cloud
• Al as a Service
• Intelligent Cloud

A major telecom company wants to enhance its contact center operations by understanding its customers better through their customer care calls, feedback survey responses, and social media interactions. Which Al and analytics application
areas will be useful? In the given scenario, speech recognition and Natural Language processing will help the business enhance its contact center operations.

Google Maps analyzes the speed of traffic through anonymous data locations from smartphones. This enables Google to suggest the fastest routes. Which technology enables Google to do this? AI and ML! Smart machines and applications are steadily becoming a daily Cloud Computing phenomenon, helping us make faster and accurate decisions.
Google Maps uses Al and ML to analyze the speed of traffic Al and ML and suggest the fastest routes.

The Winning Strategy.

What will it take to win in the new digital era? Winning strategy for future growth addressed by the following key business drivers:

Reset the rules of business.

Strategy and Innovation:

  • Accelerate innovation.
  • Redefine industry operating models.
  • Drive growth while reducing risk.
  • Enable Change adoption.

Focus on human needs.

Interactive Experiences:

  • Combine the best of human science, design thinking, user experience, and technology to provide new end-to-end services for marketers.
  • Deliver on the promise of social and brand.
  • Build Omnichannel success.

Make intelligent choices.

AI & Analytics:

  • Build intelligence-based businesses.
  • Make data an asset, not a liability.
  • Apply Analytics and Al platforms to fuel growth.

Enable the internet of things.

Connected Products:

  • Instrument and connect everything.
  • Rapid prototyping and product development.
  • Grow revenue from data-driven services.

Build software for the digital economy.

Software Engineering:

  • Embed human-insight and design into engineering.
  • New tech for new value: Cloud Foundry stack services, micro-services, APIs, engaging interfaces, etc.
  • Application portfolio optimization.

This is how organisations leverage its Al and analytics capability to help its clients stay ahead of the competition.

Industry Aligned Solutions.

Every organization will have pre-built solutions to address the needs of the vertical markets. For example,
Google’s Product Data Management solution, which uses Product Intelligence as a service offering,
caters to the needs of the Consumer Goods and Retail verticals. These pre-built solutions are easy to
customize and can be deployed quickly.

Some of the vertical markets:

  • Banking.
  • Insurance.
  • Life Sciences.
  • Healthcare.
  • Manufacturing & Logistics.
  • Comm & IME & Tech.
  • Energy & Utilities.
  • Consumer Goods & Retail.
  • Travel & Hospitality.

Case Study: Opioid addiction and early detection of drug-seeking behavior.

Challenge:

A healthcare firm approached Google for a solution to reduce the number of deaths due to drug misuse.

Solution:

Google developed an Al solution that could seamlessly scan through a physician’s prescription notes and mine for indicators of drug-seeking behavior.

Outcome:

Google’s solution helped the healthcare firm save more than $60M by identifying around 85000 drug seekers before they turned into addicts.

Summary

So far, we have discussed six strategic offerings include:

  • Insight to Al.
  • Adaptive Data Foundation.
  • Risk and Fraud Intelligence.
  • Customer 360-degree Intelligence.
  • Business Operations Intelligence.
  • Product Intelligence.
  • Organizations will have pre-built solutions to address the needs of vertical markets.

Overview of Analytics- Industry Level!

In this article, we will discourse on organizational level Analytics, Data Science, and its use cases in the corporate world, Machine Learning and its types and use cases, Deep Learning and how does it work.

What is Analytics

Analytics is the study of data, collected from various sources, to gain insights into a problem.

Types of Analytics

What is Data Science?

Data science uses a mix of tools, robust programming instructions, and principles of machine
learning to process large amounts of unstructured and semi-structured data, to:

  • Identify Patterns from the Collected Data Sets.
  • Identify the Occurrence of a Particular Event in the Future.
Identify Patterns from the Collected Data Sets. Identify Occurrence of a Particular Event in Future.

Data Science Use Cases.

Let us look at a few examples of how data science is providing valuable insights to organizations.

What Is Machine Learning?

Machine learning (ML) takes off from where data science ends. While data science relies completely
on programming instructions to detect patterns, ML is adaptive in nature. It gives computer systems
the ability to learn and make predictions by processing data and experiences.

Types of Analytics Used by Machine Learning

ML mainly uses predictive analytics.

Given here are a few key features of predictive analytics.

Machine Learning Use Cases

Let us look at a few examples of how ML algorithms are using insights provided by data science to
make predictions.

What Is Deep Learning?

Deep learning is an advanced form of ML. It processes a huge amount of data, collected from a wider
range of data sources, and requires very fewer data preprocessing by humans.

Difference between Deep Learning and Machine Learning

How Does Deep Learning Work?

Deep learning uses interconnected layers of software-based calculators, known as “neurons.”
Together, the “neurons” form a neural network, which can ingest a vast amount of data and processes
them through multiple layers. Each layer learns something about the complex features of the data.
Finally, the network makes a determination about that data, assesses whether the determination is correct,
and applies what it has learned to make determinations about new data.

For example, once a neural network learns what an object looks like, it can identify that object in a new image.

In this article, you have learned that:

  • Analytics is the study of data, collected from various sources, to gain insights into a problem.
  • Data Science gives organizations insights into business problems by processing semi-structured and unstructured data.
  • ML algorithms use insights provided by data science to make predictions about future events.


Why Customer Analytics is prime to make better business decisions?

Business analytics uses financial analytic tools to make better business decisions, but will also show you how to manage people through people analytics, will help you understand customers and markets through customer analytics, and will help you master logistics and supply chains through operation analytics.

The whole idea of customer analytics is a relatively new concept, while the overall idea of marketing has been around forever, there are so many cool and challenging data structures and technologies and decisions that firms are making and we want to help you get an understanding of them.

Let us consider the problem statement and we will find a solution using predictive analysis

Organization: A non-profit organization supported primarily by contributions from its benefactors

Challenge: Looking at benefactors’ histories of whether or not they gave each year, what can we predict about their future giving patterns?

Focal donors: Initial focus on 1995 cohort, ignoring donation amount

11,104 first-time supporters who made a total of 24,615 repeat donations over the next 6 years

HOW MUCH WILL DONORS GIVE IN THE FUTURE? HOW DOES IT DEPEND ON THEIR PAST PATTERNS?

LET’S FIRST LOOK AT “BOB”:
WHAT CAN WE PREDICT ABOUT HIS GIVING IN 2002-06?

WHAT CAN WE TELL ABOUT “SARAH”?

HOW DO “MARY” AND “SHARMILA” COMPARE?

WHAT DONATION BEHAVIOR CHARACTERISTICS DO WE NEED TO TAKE INTO ACCOUNT?

GIVING BEHAVIORS

RECENCY: How recently did the donor give? When was the last time the donor gave?

FREQUENCY: How many times did the donor give in the past 6 years?

Most meaningful donation patterns can be described by these two metrics alone.

DONOR TYPES

A L I V E : Clearly an active donor: giving frequently and gave recently

DORMANT: Has not given recently, but is likely to give again with the right development prompts

LAPSED: Has not given recently and is not likely to give again

LET US LEARN MORE ABOUT RECENCY AND FREQUENCY

Y Y N N N N

Y Y N N Y Y

What does it mean when there,s one or more “no donation” at the end of a sequence?

  1. a)  The donor lapsed (i.e., left the donor pool)
  2. b)  The donor is dormant (i.e., decided not to give that year, didn,t think ofgiving, etc.)
  3. c)  We don,t know, but can build a model to come up with a “best guess”

Answer: c) We never know for sure whether the donor is lapsed or not; based on recency and frequency of his donation, we can make an educated guess about the probability of lapsing, so we can decide where to devote resources

Based on our best guesses about the probability of “death” and propensity to donate, we can calculate expected frequency of future donations for each donor

WHAT ABOUT “MARY” VERSUS “CHRIS”?

Look, the fact is, that Mary and Chris both gave most recently and both R (Recency) and F (Frequency) are same. We know that they were alive last period, we know that they were alive at the period before that. But in some cases, if we don’t have really good information to do that sorting out, we might as well go with a tie, and I think that would be appropriate in the case of Mary and Chris.

“BUY TILL YOU DIE” MODEL

We employ a “Buy Till You Die” model to predict future donation behaviors

The model only uses three inputs: 

1. Recency (R)

2. Frequency (F)

3. Number of people for each combination of R/F
This requires a small amount of data and provides an easier structure to work

with (i.e., data are aggregated from individual-level to R/F groups)
By assuming certain probability distributions for donors, propensities, we can

construct a robust model that is easy to implement on Excel

This “BTYD” modeling approach has a long track record of success in a variety of different domains