What Are the Steps to Cast INT in SQL for Type Conversion?

What Are the Steps to Cast INT in SQL
  • Author Avatar
    Written by:

    Nathan Rosidi

Cast INT in SQL is a must-know for anyone even remotely interested in data handling and analysis. This article will cover all the important cast INT topics.

Data type conversion is one of the essential tasks in data management and analysis. In this article, we’ll take a closer look at a very distinct conversion type – converting INT data type to other data types and vice versa.

We’ll explore some typical situations and pitfalls you can encounter when converting INT. There will also be several interview question examples to showcase how this conversion works.

What is Casting INT in SQL?

Casting or converting data types in SQL means changing a value from one data type to another.

Specifically, casting INT means converting the integer data type to another data type – typically a numerical one – and vice versa.

The standard SQL function for conversion supported in all databases is CAST() or  CAST AS SQL Function. Another function that does the same job is CONVERT(), but it’s SQL Server-specific.

Situations Where Casting INT is Necessary in SQL

In general, there are four typical situations where casting to or from INT will be necessary.

Situations Where Casting Int Is Necessary in Sql

1. Data Calculations

It’s very common that performing, data calculations involves mathematical operations on two or more different numerical data types.

For example, the number of rides is stored as DECIMAL, the same as the number of passengers. If you want to calculate the average number of passengers by ride for each driver, you’d divide the number of passengers by the number of rides.

However, you should cast the values to DECIMAL before that, as you want to show this ratio as a decimal number. Otherwise, you’d end up with incorrect results, as multiplying an integer with a decimal results in an integer. In other words, you’d lose decimal points.

2. Data Standardization

Another example is when you want to ensure data types are consistent and logical, considering the data they should represent.

For instance, order IDs are often stored as INT. Usually, the discount rate would be stored as a numerical type. But it can also happen that it’s VARCHAR.

With this data being VARCHAR, you can’t do any mathematical operations, e.g., calculating the discount amount by multiplying the amount with the discount rate. So, it’s recommended to cast the discount rate to INT and make data ready for further calculations.

3. Transferring Data Between Systems

Different systems can use different data types for the same data. If you have to move data from one system to another, the data types have to match the goal system data type requirements. So, you’ll have to convert all integers to, say, FLOAT. Otherwise, you risk incompatibility, data loss, and corruption.

4. Error Prevention

Error, in this case, means type mismatch when incompatible types are used in operations or functions.

For example, you might want to concatenate the order ID with the hyphen and customer name to get, e.g., 1-Art Vandeley.

Sure, you can use CONCAT(). However, this won’t work because the order ID is an integer. So, you first need to convert it to VARCHAR, as CONCAT() works only with textual data. Only then can you proceed with concatenation.

Overview of the Steps Involved in Casting INT in SQL

Casting is not complicated and consists of four relatively simple steps. However, the most important is the first one; the other three steps are just technicalities.

1. Identify the Need for Casting: The most important step is to recognize the need for casting INT in SQL. If you don’t, your query won’t run or, even worse, it will return incorrect results.

2. Choose the Function for Casting: This step applies only to SQL Server users; they can choose between CAST() and CONVERT(). Users of other databases will have no choice but to use CAST().

3. Write the Query: In this step, you write the query that implements the casting function to cast to or from INT.

4. Check the Output: Don’t just accept the query output. Check if the conversion yielded the expected result and without errors.

Understanding Data Types in SQL

When casting INT in SQL, it’s important to know the characteristics and the use of the most common data types. Knowing that is crucial to determine, first, if the data conversion is necessary and, second, if the chosen data type fits the kind of data you want to show.

Here’s an overview of the most common data types.

Casting Int in Sql is Important to Understand Data Types

When I talk about choosing the right data type for the data, this involves considering several things.

1. Size and Range: The data type must be able to store the required range of values. For example, don’t use CHAR, which has a maximum of 255 characters, if it’s highly likely your data will go beyond that. Use VARCHAR, which can go up to 65,535 characters.

2. Storage: You should also think about the storage space. In other words, if you know INT will suffice for sure, then don’t use BIGINT just because you can.

3. Precision: Considering precision is important when casting INT to another numerical type. Yes, you want decimals, but how precise should the values be? If you want exact values with the controlled number of decimal places to avoid rounding errors, then use DECIMAL. If you’re fine with approximate values, use FLOAT.

The Syntax for Casting INT in SQL

The CAST() syntax is as follows.

CAST(expression AS data_type)

The expression is data written in single quotes ('') or, more often, a column name you want to cast. After the keyword AS, you define the output data type.

In PostgreSQL, you can use a shorthand for CAST(), which is a double colon (::).

expression :: data_type

The SQL Server users might also want to use CONVERT(). It has a very similar, the-other-way-round syntax.

CONVERT(data_type, expression, [style])

So, here, you first define a data type and then refer to the data you’re converting. All the arguments are separated by a comma. CONVERT() also has the optional style parameter. It defines the format for the conversion. This is mainly used when converting date/time data types to and from string data types, so you won’t be needing this when converting INT.

Comparison of CAST() and CONVERT() for Type Conversion

As CAST() and CONVERT() do exactly the same thing, let’s see how to use either of them in a simple example.

Example #1: Casting to INT

This question by Yelp explicitly asks to cast one column, namely stars, to INT. Apart from that, all other columns from the table yelp_reviews should be shown, and the non-integer values from the column stars should be removed.

EasyID 10056

Cast stars column values to integer and return with all other column values. Be aware that certain rows contain non integer values. You need to remove such rows. You are allowed to examine and explore the dataset before making a solution.

Go to the Question


Link to the question: https://platform.stratascratch.com/coding/10056-cast-stars-column-values-to-integer-and-return-with-all-other-column-values

Here’s the dataset preview.

Table: yelp_reviews
Loading Dataset

The column stars, which we have to convert to INT, is defined as VARCHAR.

Solving this question using CAST() means that we reference the column stars in the function and define the output data type as INT.

In addition, we can exclude the question mark character from the same column, as it is not an integer.

How do we know there are no other non-integer characters in this column? Well, the question allowed us to explore the dataset before writing a solution.

SELECT business_name,
       review_id,
       user_id,
       CAST(stars AS INT) AS cast_stars,
       review_date,
       review_text,
       funny,
       useful,
       cool
FROM yelp_reviews
WHERE stars <> '?';

PostgreSQL

You have reached your daily limit for code executions on our blog.
Please login/register to execute more code.

Here you have the output.

All required columns and the first 5 rows of the solution are shown

business_namereview_iduser_idstarsreview_datereview_textfunnyusefulcool
AutohausAZC4TSIEcazRay0qIRPeMAFgjlbPUcCRiXlMtarzi9sW5w52011-06-27Autohaus is my main source for parts for an old Mercedes that has been in the family since new that I am restoring. The old beater is truly a labor of121
Citizen Public HouseZZ0paqUsSX-VJbfodTp1cQEeCWSGwMAPzwe_c1Aumd1w42013-03-18First time in PHX. Friend recommended. Friendly waitstaff. They were understaffed and extremely busy, but we never knew. The short ribs were tende000
Otto Pizza & PastrypF6W5JOPBK6kOXTB58cYrwJG1Gd2mN2Qk7UpCqAUI-BQ52013-03-14LOVE THIS PIZZA! This is now one of my favorite pizza places in phoenix area. My husband i walked into this cute family owned business and were greet000
Giant HamburgersQBddRcflAcXwE2qhsLVv7wT90ybanuLhAr0_s99GDeeg32009-03-27ok, so I tried this place out based on other reviews. I had the cheeseburger with everything, some fries, and a chocolate shake. The burger was okay, 011
Tammie Coe CakesY8UMm_Ng9oEpJbIygoGbZQMWt24-6bfv_OHLKhwMQ0Tw32008-08-25Overrated. The treats are tasty but certainly not the best I have ever had. I would have rated this a two star but the cakes and cookies are REALLY pr132
Marcellino RistoranteGTUOIBCEGGt_aGp-bRogfggopGuEb-ft6cHKMyCZEvJg12010-12-17This place sucks. Food was average and we had to wait an hour even though we had a reservation. My americano tasted like warm soy sauce and they blame230
Shanghai ClubwHfxd0Bq4JYLiUEO55xe4QeVQ_yDkMlF62oofUwc29Kw52013-09-19This is our favorite Chinese restaurant in the area! The service is always consistent and our favorite waitress - Becky - always makes time to spend w000
Freddys Frozen Custard & SteakburgersNfTR_B1yW1hPVEoXlSJV-wYnHYlN1m7jDhAH9XgR4Dlg42013-01-24Love the tiny fries.100
Chipotle Mexican Grillk-Oo0Gs4AC04GJAecu_iWgHjpzhIQFRQbFmc_7CtFDmg42011-05-11When you don't feel like a full restaurant and you want more than the normal Mexican fast food, Chipolte fits the bill. The food is always fresh, the000
Arizona Fire & Water RestorationuvVmBnYQf8Mnt-s64D8XOgzQP7cLujr-MJ207uuNFC1w52011-08-03This is a fantastic company. They have a very high rating with BBB and have won a ton of customer service awards. Hopefully you dont need them but i000
Arriba Mexican Grill0HOrc_RX87-01dbdFMSjJw8m8HQtZox4vS-N-AW3mzxw52013-12-31Open Christmas Day! Their food is delicious. Especially breakfast! Mmmm, the salsa mmmmm. Hatch chills, pork, chicken...pollo asada, carne asada...you110
Renegade Tap & KitchenZaCA3v9bWUpHuwZ6NO8C1QiVTzpbZ6qBdFllvcJLbmeg42011-02-26Dinner on a busy Friday night. Arrived on time for 7:30 reservation. Table not ready, restaurant and bar full. Host and hostess pleasant, but not o001
Chipotle_gcGIGfziNkhaIlkjhjKHg3uU_6L8GnFOHTsO4I3oedg32013-09-24I absolutely looove Chipotle. My problem is when you make me pay almost $2 extra for guacamole... please don't be stingy with it. Hook it up, Chipotl121
SanTan VillageLXiDBkXxcyL4IPnXbjw0VQBa-tIR3a8hhwIk-y_hVzFg42011-03-27Next month when the temps skyrocket to triple digits, i will prolly not think soo highly of this place, but for now, San Tan has gotten alot of my fre012
Love'sEr4Y-yj1JBW9cCbIf3ViKgbC3By-saT9ylKu-dwWgtcw42012-11-13Plenty of gas pumps and convenient to get some cooked food inside. If getting gas, caution for enter and exits at pumps.000
Dirty DrummertMYUWXoFuLdFecqqP60R3AX_kPh3nt0AJPNPHye2rTlA42011-06-18I was introduced to this place by my coworker and friend. She goes here every single day at lunch and its cute because everyone knows her there! Any132
Euro Pizza Cafex2atXyt-QwCTzHhglzxj3QJKp42Y520azWI_WBzUMxTw52012-04-07This is a nice cafe with a diverse menu. There's indoor or outdoor dining with a view of the famous fountain! I ate here with my friend Connie who als001
US Airwayso_YetnCcK_96ueIULO84fAVl4k0FiMNCRzEQwOpe4hXw22012-07-20Well, they have good flights and connections from time to time. Their fleet is very archaic though, probably most of their planes are older than me (a010
Wal-Mart Neighborhood Marketc7JHcdWo5pZ3rMIDbsDt_gIDHrwv_RCildFvmfWTkj5Q22011-10-02I occasionally stop in this store while driving past. I will try to keep my comments on the positive side. NOTE if you don't read anything else: if 011
Flancer's Cafe78XeKBmSE0reBjsmqg7HNgAYGHNy8gPxl2Q-etTT3hZw32012-12-01This place has decent food, cute atmosphere, but the service is problematic. I was stuck in Mesa for training and had lunch there on Halloween. My pal575
Pappadeaux Seafood Kitcheny6q-inMFFoEci-wRATp1-AS3bvMOL50vgS_8-TtlGi4w12010-12-02$20 for a double Maker's Mark? Me thinks not T.G.I. McPappadeaux. I was not impressed by anything that was there and will not only steer clear but m1366
Lone Star Steakhousefp73RBYM6NAnNWii9bxZ8w7Ot-v89x44U_VdIPgD3qKg42011-10-18Great food and a rare bird of a honest manager when it comes to whats in the food. They have very comfy booths. Did nor care for the country music. I000
EVO3D3Avu2d8Gj-HEbqqWhswgH982l-WK1p49z9jZFNMEfQ42013-12-29Great atmosphere and decor..a welcome change from the chains and anchor restaurants in the area that all feel the same. My wife could not stop raving000
Conocido Park0ESAQ8Ynk1nZPt5LayMwng3OelvbzNK3KSmMdL0O9nRQ42013-10-08I play this disc golf course weekly. The baskets are frequently moved to keep the course fresh. Trees provide difficulty and also shade! There are Dis010
Nate's Barber ShopKEMsCW33Y1ZQEGTiMKmcrAHm_7pViZyrp_Z62lBRopAg52012-12-12Nates barber shop is one of the best shops that I have encountered in my life. If your looking for a great inexpensive ($13) good looking haircut this000
S & S Tire and Automotive Service Center99_nV5h4JHomT7cgh0V6lghYKjQHu2fk4nMgCWO50f-w52011-02-25My partner and I needed two new tires and an alignment. We have a Chevy Cobalt and its only two years old. Went to the dealership and they wanted almo100
La Parrilla SuizaldvKeuzBSIesZEmFcr4ooQEXvhtd_05d1H9RlXa2CnIQ52012-07-27This food is just....fantastic. I don't know what else to say. I grew up eating at La Parrilla Suiza in Tucson. The tortilla soup and "Queso Suiza"010
Scratch Pastries & BistroznMtXO5hY5XPqAMj_7VLRgb2DKC4kC8-QeSeGZ_MF3XQ52012-03-16Yes, it is in a strip mall. Don't let that fool you. This is some downright good food with affordable prices. Even though service was very attentive 000
Joyride Taco HouseuyLuLYfjs3S_8u3OkrIdmwmY6zzvFbK0ENnQOdgtiT4Q22013-10-19Great food! But not worth the HORRIBLE SERVICE! Took about 15 mins for drinks that included a dr pepper. The server said the bartender is working hard232
In-N-Out BurgernxoxgQka8mTK-rLCh7sg3wOwVB3YzcYeTRV09tpNDBSA52011-07-08Nothing beats a #1 with grilled onions, no tomatoes, well done french fries and a pink lemonade. I've been known to eat here twice to three times a we000
Roka AkorfpjKqP8ONJ9rT82VoUhIQQ4ozupHULqGyO42s3zNUzOQ52011-07-18I hate to admit it, but it had been a long while since my last visit to Roka Akor. I deserve a hand slap. But last week, I had the perfect excuse to p5810
Ruth's Chris Steak Housez3pSiipCrQM3B6i9PrnoGwhJBOxmNREXmMGTfXgMcGug52010-03-30Best steak I have ever eaten is at Ruth's Chris steakhouse. Comes to your table sizzling hot. Sides are sold individually but are pretty good. The des000
Yupha's Thai Kitchenarf6Ne6h0UDXizsbMcOomQAkJFqLqHHAKY3H5R8p7cPQ52012-12-09Yupha Thai is definitely a "yuppy" in terms of being a great spot to go to. There are not too many places to eat near ASU Research Park, which is rig000
Hotel Indigo ScottsdaleVDtEMw1X397ViDlP7oErTw8Oy9-UwJQWffS0yOwPG6Ew42013-07-01I stayed here for one night while on a recent business trip! I wish I had discovered this place sooner.... I was pleasantly surprised! I never heard 000
Da VˆngxbVGTBSsXmvu56FTbXp7AwF6mQhKLdj_PEdxLvDYOm2Q52011-12-15I haven't had better pho anywhere in az. the large pho is enormous for the price. i usually go with my family and order a regular sized pho for myself000
Trader Joe'sHzI7nVlXJQJR3GO1KXYxlAcMmQsFyrYBv6hIE6NffqZQ52011-01-03Trader Joe's always goes above and beyond in all of their services. The food is fresh and delicious, the prices reasonable and the people are great. 000
Beaver Choice18fIpXUbcm9k6Pmtkbf0aA3gIfcQq5KxAegwCPXc83cQ42011-04-21So I went here tonight with a friend. I was really excited and nervous to try this place after reading the reviews. So you walk in and walk up to the110
Some BurrosOqogqje3RKspPwVcREfsXAGnqNc74So5Pc8C3hkA2hCg52009-07-10Came here w/ the hubster's. I've actually been craving this for some time now. The pollo fundido is great! So goooooood! Its a pretty big portion. The021
Superstition Ranch MarketB1xnRb2j_iW2Ws0u1B0FNwEOLRikjQxTIpXB4aV1hbPQ52012-01-05Great place to shop, buy what you will use within a few days.000
Fuego TacosJ6nrjjCjXc-hnRpZZPrLnQA99dyhEqcd_yXKPfBWeZHA32011-08-18I went to a late lunch on a Saturday and the Esplanade area was quite dead (I'm surprised because in the old days ('98-'99), I remember it to be prett000
The Woodshed#NAME?lsp7p2NuC5MX4_iuch3_OA12012-06-17We only went here because it has been a traditional Father's Day event with friends. We decided to join them for the 1st time......really...we will n010
Rosati's PizzaLd4Qg2Du0S3ulcdDCdm7JgSEDJTWEzMdqp7UsS1W3KXw32012-10-24First of all, let me just say their food is fantastic. I love their pizza. I love their salads. I love the cheesy garlic bread and their chicken parm.100
Sekai Sushi8TB8vM1H_SuEK2hS-5wu7gTDlgqAxf268QOw-OUk2Urw22012-05-02I am sorry to say people of Mesa you must have pretty low standards if this is the best sushi bar in Mesa. I went there last night and I really did no020
D'Vine Bistro & Wine BarJvHH1Z84UJ1P5T9uIxEnyQrT4ycOjlrKefSAcjoQga5g42012-04-12Love the atmosphere and fantastic happy hour! Favorite spot in Mesa:)010
Scottsdale StadiumeAYq_HT_gbD_ECgIWn3GoAMt3dPqOlnlGyVCftCcokmg42012-03-27Ignoring the fact that Scottsdale Stadium is a bit overpriced these days for Spring Training Giants tickets, its fun. Its basically one big party (in 030
Thai House#NAME?fczQCSmaWF78toLEmb0Zsw42008-07-21Damn... Helen Y beat me to the punch and got the FTR for this place! Oh well, I will say that she did a great job with her review - I think I was Tha387
Jalape–o Inferno Bistro MexicanoVRiSQiIfUnZdp0CxNMkLWg4nJ5ryQTcQKs8mCrgt8-BQ22011-04-05The dinner we had here was OK... nothing to rave about. The tortilla chips were very good as others have mentioned... a mix of corn and deep fried flo000
Caffe Boahi6a3fvAbtZq9jMIM8gkwQqa05pUVNapADHZXpHMPMeA32010-06-26Caffe Boa is an interesting jokester, so, it is interestingly hard to review it. I'll keep it short. I have gone here several times, and each time wit000
Golden ValleyZYEAmRpYHxJYcbIv-c7S2wgg_OKjOAl_vVmdh5ZETuiw32012-02-25Can I tell the difference between Uzbek cuisine and other Middle Eastern or Mediterranean cuisine? Nope. For all I know it's only a matter of where000
Canyon Cafegi9hLYOPk_fbvOr2mCHu7gnH9OZEGfgseWjC5_IPGCXw52010-08-09Everything about this place is wonderful!! I love the huge windows and outdoor patio! Gorgeous! Their food is amazing everything from the chips (there001
Panda Expressr52OE-CfRoJQyjBtn0vHIQfMyKbyYY9Poy9B_1QZPKcg12010-05-31My young children love Panda Express orange chicken. They eat it 2-4 times a month. We were at the mall on a Saturday afternoon and stopped into the f000
Gordon Biersch Brewery RestaurantpfPFWY5SXQEEnlVJbFaNqAnKaR5Z9Qmqc4RsakLLX_7w32010-03-29It's very hard for me to enjoy a house brewed schwarzbier that, to me, tastes more like Bud Light with a hint of acrid smoke flavor than what I consid243
Chili's Grill & Bar42EOZ0KMF4wU1Sz7oeLfpAAfyzIHPy5zds_mqf2Jdc9g32011-02-07I love Chili's. My husband and I always go for the 2 for $20 deal at whatever Chili's location we may be, but this location seemed to skimp out on the000
Beckett's TablelNLiQx1zi-ctta6v4LLhXwGJwbccjXgoRPbNuWcNKYXA52012-01-29Beckett's Table is a fantastic restaurant for people who want great food, great wine, and great service. My wife and I dined there with a couple of fr000
My Big Fat Greek RestaurantIuSys52QuyTxGv3HLFKBSw1gY1N3pkxTzh7kK4BxANyw42011-05-07I hated Greek food, until I tried this place. My "health nut" girlfriend had to drag me to this place, kicking and screaming. After all, my long ago233
Goldmans Deli6DggWM9rgzC_mIo4THFpMAPKZvqm3IeWiWBYoDDoEG4w52012-09-02Traveled in from the east coast so I got to Arizona very early in the day. I needed to kill some time before I could check into my hotel room so I en000
Macayo's Depot Cantina98nvcyGhtHlKO8pDlOcCsAbZFRqP7s0Vszxeu8_IwYow32008-03-21I finally ate lunch here after not being able to get decent parking for Quiznos on Mill Ave. My coworker and I were starving and needed a place to sh023
Rayner's Chocolate & Coffee ShopGCdNDjutQWsT-qaYwW0zxwM28A6JPQFBJnRBCfODe8IA42013-05-15Cute bakery/coffee shop hidden in a little plaza on 51st Ave off of Thunderbird Rd. Nice selection of unique baked goods, chocolates and coffee drinks010
Sushi Brokersup3ueFZ1xJh_ts6dVu3_0AhDlSSyDreM9xY4yQWPm54w22009-02-26--expensive for business lunch --servers very attentive, prompt --lacks nth-degree detail of a Japanese chef running things; rolls and standards are s433
The Vig Uptownrib7dXO863eL5VGUDsot8guQCk37gNl1bEmkjAv6_kAw42011-04-17My meal was great; the decor / layout is great also, with a lovely patio out back. The only downsides are parking, and the fact that the entrance is a010
Lo-Lo's Chicken & WafflesIlFoK4meMZ7Ws4enESzeTQEacK6XwZjsTD6QYSIRlJ7Q52008-07-14At first most of my noobie friends are very skeptical about the fusion of Chicken and Waffles. but after taking them to this place and experiencing f232
Shoe CarnivalYhlJA_CuoZlK4FIJUHlCnw_PzSNcfrCjeBxSLXRoMmgQ22010-05-17I had a $5 coupon in the mail so I was like what the heck. And is it next to Home Goods (one of my favie home decoration stores). I got to the store i210
My Big Fat Greek RestaurantQe0FO565tGfTxb7QtNCVwg2vl3MXKr8iQOWTNse5kgdw32008-04-03Nice menu selection; food was tasty. Good atmosphere. Wished they had a restaurant in the LA area.010
Casey Moore's Oyster HouseR7ZJPW4qEXuqI41aaWmO0ArLtl8ZkDX5vH5nAx9C3q5Q42009-04-02This is a fun place for appetizers and drinks if it is not too crowded and the temperature is just right outside. Otherwise the inside gets way too p121
Q to U BBQIJxqQwzJjAURPBAB_-iOAAMSgZpSWlf8T2H_46OWNgCQ52011-09-08Really enjoyed the Ribs and fries, I came with friends that really like BBQ, they agree, the ribs were terrific! I am sure we will be going back to Q111
Lightning LubekezCWAz6MO1wKwXB_DK-3QbwmXfjwrogAaGqV33kSVpQ32013-08-24$115 for an oil change and two air filters for my civic. I must've had a really long day or she had magical powers and made me forget I could simply c011
Athens GyrosaAgVzZU2b0YbYGi4byeI6wL8_GwFxxtGSYR2F_dglpSg42013-08-17Great food nice service. The girl that worked up front introduced herself to the other patrons that were there and asked them how the food was but no000
Metro Light RaillG8Swugg_DQxY3NgT_BEigLqgGgWi3FLHBViX9tmZ9sw32011-10-31I just wish that this stupid HUGE metropolis could have more LIGHT RAIL connections!! compared to the circus you have to stand in the buses, the LR is111
Oregano's Pizza Bistro7QvgM_LJi6SRp_GuOXPFZQfor16MiFS1M_8_cne6IbIw42013-02-04Big Delicious portions!000
Gallo BlancogULD5qz_CQI9clPWh2FNHAZ02XdD0muEz2FFQKPERMYQ52013-12-29Stopped in here one night right before Christmas. Short and sweet: Margaritas - very good (and huge by the way) Tacos - awesome Guacamole - exce222
Los Dos MolinosJcWhDcyNl3r_Tbeqiac15QGoymUzKqvET2QOZkIWZi9w42014-01-07We have a friend who said the salsa is way too hot. All I heard was "you must try Los Dos Molinos". We love spicy food and are always up to a challeng011
Nancy's Nail SalonZGo8c57MrzQrSN6R7zO1uQA9g7YnTtsSV-wEIo3HI1YQ42011-06-09Came here with my sister in law she had a coupon for a 27.99 mani/ spa pedi. The staff was friendly they have a tv and plenty of magazines to look thr010
Changing Hands Bookstore1xzMe1EEwhF23RNh3InKkQfPHLPrymsyb6WSFFKoMrTQ52010-10-26This not-so-little bookstore has it all... new and used books, a unique gift section, book signings and events, wonderful staff and a cool, organized,001
Tortilla FishOmSYYxZskG9BeRMwb5DltwMxO7EY766jVoFEZzkpwmOQ22013-10-06My experience wasn't bad, just not up to the hype of all the other reviews. I tried the shrimp, fish, campechana and machaca tacos. The shrimp tacos w000
Pet Club0LvO1yc-52fJ6vIHaFVdAwLXOhR4ZUULSbBNztxYZ2dQ22013-07-16That awkward moment when local competitors come write negative reviews about a store and then direct traffic to their own store....011
Taste of TopsJ2lGBvJOcuhmauWs3rgMSgaIAjAU-6NH583EkQ6E9KRw42009-10-09Okay, in interest of full disclosure, I literally live around the corner and across the street from Tops Liqour and have been waiting forever for this111
Carolina's Mexican FoodN6eg6Jc_mL_XHMGmw6GElwcbxUyCUMjkWAs1h4auYeAw42012-01-31If you're looking for real Mexican in a hurry this is your place. This is one of places ill always bring out of town guests who can't find good Mexica001
Super L Ranch MarketcK3J7FAqruLZM_Y5J29Q8Qz06IHGXI_ofBc2DkAbCgnA52011-05-09HOLY CRAP THEY HAVE FROZEN XIAOLONGBAO. :) These delicious little bites of porky, soupy dumpling heaven have eluded me since I first tasted them in 221
Salt CellarIXGX_Lk2NgCH-0OQNcGMpQE4HbTIHd9PVjUnEKpysaLw52011-10-04My experience here was absolutely amazing. My boyfriend and I had reservations for 7:30 pm on a Saturday night and the service was amazing and the fo021
Rosita's Placef_yQqlsim0S9YAIIYFvR5Q7nlZJW84Adt6oYn2shnn_g32013-05-30The food here is delicios, but it takes forever. From the time I ordered to when I was served 25minutes. Come only if you have time to spare to sit an000
Matador Restaurantx927gFqVNPSOPwNrKqPmmQnyHh14Vb9S269-kGKaUelg42011-08-09I've eaten at Matador almost once a month for about15 years. I won't get into the logistics of others reviews. I give the higher than average star rat001
Hanny'sriZp_RIN28ld-U2Q5dhKhAGRgBu4K7GOb3354esp_xkg42010-06-08Food = 4 stars Place = 5 stars Service = 4 stars I REALLY like this place. It looks super classy inside and the deco on both floors is a333
Crust Pizza and Wine CaferTc3d_GYXyHuf_tQoED80gAOmdmYYSeLUstcN084_wMA12012-10-16I told my friend that I'd rather eat out of a vending machine, and he said.. "Yelp THAT!" I had the calamari app, the caprese salad and the eggplant210
Ocean Air9gLTx4HjE-NeSa3KTfGJJQK0U0Hp6rgXHrYCG4jpPT8w52013-09-01Thank you! Ocean Air came highly recommended and now I know why!! Excellent, fast, friendly service!!! Reasonably price AC maintenance and FAST respon000
Sleepy Dog Brewpub9gtyU7vjWUjddmFrT97swwFm0EXFwIfDQoIm9RgcAOKQ32013-04-06As a number of others have said, the beer is good with a good number of choices. The food is pretty good too. The biggest issue has been service. The000
unPhogettableyVK0x3_-o16ufBbIyqGJRwsWh4Tjwa8ch_rziHtTN9LA52013-08-27Always amazing service! Always amazing pho! Add veggies to a meat dish! The spring rolls A1 & A6 are the best in town!!! We are now here on a weekly b111
Paradise Valley Burger CompanybkZ67PfRlKLKl4x5mIFYSgff00OcqImnNYy-OvSgUZyw52013-11-04Best burgers in town! They don't skimp on quality or ingenuity.000
Hanny's4n_3G2Xux0stcgOUsrzYawev7D2jo5OUDeHf0dWoWlsQ22012-06-25Super disappointing, they won't take reservations and I wanted to make a reservation for 20 persons. I've been here many many times and love the food 002
Golden PandaikNpO72tj7uI5VTatHpoAA80OFMLRA0yW3sE4ciYg_vA12009-10-10Why oh why is it so hard to find good Chinese food in this town? The two behind the counter at this place are Chinese - please don't tell me you eat000
Breakfast ClubU_oJEB166nCeBNY-wqadxwAMYi-53cxstrCR5wqyY1KA52011-01-11O-M-Goodness! What luck to have eaten here for breakfast!! Huge portions served with fresh fruit slices or mixed berries. Great service and very nice000
Ulta Salon Cosmetics & Fragrance9e3MOWg4zrq_NOqKP3fMcQF6QsMoJdvtohlbnST-fDyQ42011-03-14I really like this store and have been going here for as long as they have been open. 18 or 19 years. It is always exciting to be rewarded for the pro110
Essence Bakery CafŽNkekoPY-4txUxkyoN_Tu4wDrWLhrK8WMZf7Jb-Oqc7ww52012-09-14Ok, I'm not sure I ever had this pastry combination, but it was clearly a great item. It was the Chocolate almond croissant. Usually those two varieti010
zpizzaUJEPSoO6yNnR8kdneDy0rgfSi-yrKtBD58h2vPxjNE1A42010-12-01We ordered 4 rusticas for delivery using their buy-one-get-one promo online. They had a great deal on rustica pizzas, but somewhere in the fine print 211
Kona GrillosYRF4FQe4cziGIXz33eQQgITFg65GtRDUb-0n460vNg42011-03-17I've eaten at Kona Grill twice in two days while doing business in the area. I had the Kona Burger and the Pepperoni Pizza. The burger was fantastic000
White Housexn2LkVHBuRZ_jAg-LIiQ4QwFweIWhv2fREZV_dYkz_1g42011-07-25It's been a while since I took part in the nightlife in Scottsdale, it's not my scene but I was invited to White House for a party so you know how tha354
Crowne Plaza Resort Hotel San Marcos Golf ResortbMKW11Cf1Zeu1zWkzDbtrQKt9NwDONle_mc0QHTud9jw12011-07-18Rating the golf course, horrible!! Thank goodness there was no one in front of us and we zipped around the course. They clearly stopped maintaining 000
Hon Machimu8Gst6LkzG5ahmolCH55gKucBnMrhalzxnD9AWrxwYQ52011-06-21Great place for sushi and tepan - period. Not the "high-end" places but a rock solid place with lots of variety and good prices.010
Bourbon Steak a Michael Mina RestaurantAA6QQUFGWWkZlbpat46OfQcEIeuU0-4fX0Y4qCUW3PwQ22008-12-01My husband, some friends and I went to this place for restaurant week. We all sampled different dishes to experience a range of items - the multi-flav012
Tempe's Front PorchJ71o5dOSoxoOhcR8NEo4OgR4Ax3btoJ6qLXhqq6J50VQ42014-01-06This is the front porch of Monti's, my boyfriend and I were pretty confused looking for it. It's outdoors with a bunch of heating lamps, be sure to s121
Joyride Taco HousepKe_ORPqaW0vfGyFkbxdHwxv9nUSKR5RqnkgD0tufTfA42013-12-02Tried this place tonight with my boo and I am definitely a fan. He loved his carne asada burrito and my enchiladas were super tasty. They are a littl000
LunardisfpjKqP8ONJ9rT8209thIQQ9itypHULqGyO42s3zNUzOQ52018-06-11This is the nicest grocery store in the city. I actually met my wife at this grocery store while shopping for avocados.6710

CAST() has the same syntax in all databases, as it’s ANSI standard. In addition, PostgreSQL allows the use of a double colon operator instead of CAST(), so casting is even simpler.

PostgreSQL

You have reached your daily limit for code executions on our blog.
Please login/register to execute more code.

The output is, of course, the same.

In SQL Server, you have the option to use CONVERT() instead of CAST(). In that case, the output data type is defined first, and then the column stars is referenced.

SELECT business_name,
       review_id,
       user_id,
       CONVERT(INT, stars) AS cast_stars,
       review_date,
       review_text,
       funny,
       useful,
       cool
FROM yelp_reviews
WHERE stars <> '?';

MSSQL

You have reached your daily limit for code executions on our blog.
Please login/register to execute more code.

You can see that CONVERT() returns the same output as CAST().

All required columns and the first 5 rows of the solution are shown

business_namereview_iduser_idstarsreview_datereview_textfunnyusefulcool
AutohausAZC4TSIEcazRay0qIRPeMAFgjlbPUcCRiXlMtarzi9sW5w52011-06-27Autohaus is my main source for parts for an old Mercedes that has been in the family since new that I am restoring. The old beater is truly a labor of121
Citizen Public HouseZZ0paqUsSX-VJbfodTp1cQEeCWSGwMAPzwe_c1Aumd1w42013-03-18First time in PHX. Friend recommended. Friendly waitstaff. They were understaffed and extremely busy, but we never knew. The short ribs were tende000
Otto Pizza & PastrypF6W5JOPBK6kOXTB58cYrwJG1Gd2mN2Qk7UpCqAUI-BQ52013-03-14LOVE THIS PIZZA! This is now one of my favorite pizza places in phoenix area. My husband i walked into this cute family owned business and were greet000
Giant HamburgersQBddRcflAcXwE2qhsLVv7wT90ybanuLhAr0_s99GDeeg32009-03-27ok, so I tried this place out based on other reviews. I had the cheeseburger with everything, some fries, and a chocolate shake. The burger was okay, 011
Tammie Coe CakesY8UMm_Ng9oEpJbIygoGbZQMWt24-6bfv_OHLKhwMQ0Tw32008-08-25Overrated. The treats are tasty but certainly not the best I have ever had. I would have rated this a two star but the cakes and cookies are REALLY pr132
Marcellino RistoranteGTUOIBCEGGt_aGp-bRogfggopGuEb-ft6cHKMyCZEvJg12010-12-17This place sucks. Food was average and we had to wait an hour even though we had a reservation. My americano tasted like warm soy sauce and they blame230
Shanghai ClubwHfxd0Bq4JYLiUEO55xe4QeVQ_yDkMlF62oofUwc29Kw52013-09-19This is our favorite Chinese restaurant in the area! The service is always consistent and our favorite waitress - Becky - always makes time to spend w000
Freddys Frozen Custard & SteakburgersNfTR_B1yW1hPVEoXlSJV-wYnHYlN1m7jDhAH9XgR4Dlg42013-01-24Love the tiny fries.100
Chipotle Mexican Grillk-Oo0Gs4AC04GJAecu_iWgHjpzhIQFRQbFmc_7CtFDmg42011-05-11When you don't feel like a full restaurant and you want more than the normal Mexican fast food, Chipolte fits the bill. The food is always fresh, the000
Arizona Fire & Water RestorationuvVmBnYQf8Mnt-s64D8XOgzQP7cLujr-MJ207uuNFC1w52011-08-03This is a fantastic company. They have a very high rating with BBB and have won a ton of customer service awards. Hopefully you dont need them but i000
Arriba Mexican Grill0HOrc_RX87-01dbdFMSjJw8m8HQtZox4vS-N-AW3mzxw52013-12-31Open Christmas Day! Their food is delicious. Especially breakfast! Mmmm, the salsa mmmmm. Hatch chills, pork, chicken...pollo asada, carne asada...you110
Renegade Tap & KitchenZaCA3v9bWUpHuwZ6NO8C1QiVTzpbZ6qBdFllvcJLbmeg42011-02-26Dinner on a busy Friday night. Arrived on time for 7:30 reservation. Table not ready, restaurant and bar full. Host and hostess pleasant, but not o001
Chipotle_gcGIGfziNkhaIlkjhjKHg3uU_6L8GnFOHTsO4I3oedg32013-09-24I absolutely looove Chipotle. My problem is when you make me pay almost $2 extra for guacamole... please don't be stingy with it. Hook it up, Chipotl121
SanTan VillageLXiDBkXxcyL4IPnXbjw0VQBa-tIR3a8hhwIk-y_hVzFg42011-03-27Next month when the temps skyrocket to triple digits, i will prolly not think soo highly of this place, but for now, San Tan has gotten alot of my fre012
Love'sEr4Y-yj1JBW9cCbIf3ViKgbC3By-saT9ylKu-dwWgtcw42012-11-13Plenty of gas pumps and convenient to get some cooked food inside. If getting gas, caution for enter and exits at pumps.000
Dirty DrummertMYUWXoFuLdFecqqP60R3AX_kPh3nt0AJPNPHye2rTlA42011-06-18I was introduced to this place by my coworker and friend. She goes here every single day at lunch and its cute because everyone knows her there! Any132
Euro Pizza Cafex2atXyt-QwCTzHhglzxj3QJKp42Y520azWI_WBzUMxTw52012-04-07This is a nice cafe with a diverse menu. There's indoor or outdoor dining with a view of the famous fountain! I ate here with my friend Connie who als001
US Airwayso_YetnCcK_96ueIULO84fAVl4k0FiMNCRzEQwOpe4hXw22012-07-20Well, they have good flights and connections from time to time. Their fleet is very archaic though, probably most of their planes are older than me (a010
Wal-Mart Neighborhood Marketc7JHcdWo5pZ3rMIDbsDt_gIDHrwv_RCildFvmfWTkj5Q22011-10-02I occasionally stop in this store while driving past. I will try to keep my comments on the positive side. NOTE if you don't read anything else: if 011
Flancer's Cafe78XeKBmSE0reBjsmqg7HNgAYGHNy8gPxl2Q-etTT3hZw32012-12-01This place has decent food, cute atmosphere, but the service is problematic. I was stuck in Mesa for training and had lunch there on Halloween. My pal575
Pappadeaux Seafood Kitcheny6q-inMFFoEci-wRATp1-AS3bvMOL50vgS_8-TtlGi4w12010-12-02$20 for a double Maker's Mark? Me thinks not T.G.I. McPappadeaux. I was not impressed by anything that was there and will not only steer clear but m1366
Lone Star Steakhousefp73RBYM6NAnNWii9bxZ8w7Ot-v89x44U_VdIPgD3qKg42011-10-18Great food and a rare bird of a honest manager when it comes to whats in the food. They have very comfy booths. Did nor care for the country music. I000
EVO3D3Avu2d8Gj-HEbqqWhswgH982l-WK1p49z9jZFNMEfQ42013-12-29Great atmosphere and decor..a welcome change from the chains and anchor restaurants in the area that all feel the same. My wife could not stop raving000
Conocido Park0ESAQ8Ynk1nZPt5LayMwng3OelvbzNK3KSmMdL0O9nRQ42013-10-08I play this disc golf course weekly. The baskets are frequently moved to keep the course fresh. Trees provide difficulty and also shade! There are Dis010
Nate's Barber ShopKEMsCW33Y1ZQEGTiMKmcrAHm_7pViZyrp_Z62lBRopAg52012-12-12Nates barber shop is one of the best shops that I have encountered in my life. If your looking for a great inexpensive ($13) good looking haircut this000
S & S Tire and Automotive Service Center99_nV5h4JHomT7cgh0V6lghYKjQHu2fk4nMgCWO50f-w52011-02-25My partner and I needed two new tires and an alignment. We have a Chevy Cobalt and its only two years old. Went to the dealership and they wanted almo100
La Parrilla SuizaldvKeuzBSIesZEmFcr4ooQEXvhtd_05d1H9RlXa2CnIQ52012-07-27This food is just....fantastic. I don't know what else to say. I grew up eating at La Parrilla Suiza in Tucson. The tortilla soup and "Queso Suiza"010
Scratch Pastries & BistroznMtXO5hY5XPqAMj_7VLRgb2DKC4kC8-QeSeGZ_MF3XQ52012-03-16Yes, it is in a strip mall. Don't let that fool you. This is some downright good food with affordable prices. Even though service was very attentive 000
Joyride Taco HouseuyLuLYfjs3S_8u3OkrIdmwmY6zzvFbK0ENnQOdgtiT4Q22013-10-19Great food! But not worth the HORRIBLE SERVICE! Took about 15 mins for drinks that included a dr pepper. The server said the bartender is working hard232
In-N-Out BurgernxoxgQka8mTK-rLCh7sg3wOwVB3YzcYeTRV09tpNDBSA52011-07-08Nothing beats a #1 with grilled onions, no tomatoes, well done french fries and a pink lemonade. I've been known to eat here twice to three times a we000
Roka AkorfpjKqP8ONJ9rT82VoUhIQQ4ozupHULqGyO42s3zNUzOQ52011-07-18I hate to admit it, but it had been a long while since my last visit to Roka Akor. I deserve a hand slap. But last week, I had the perfect excuse to p5810
Ruth's Chris Steak Housez3pSiipCrQM3B6i9PrnoGwhJBOxmNREXmMGTfXgMcGug52010-03-30Best steak I have ever eaten is at Ruth's Chris steakhouse. Comes to your table sizzling hot. Sides are sold individually but are pretty good. The des000
Yupha's Thai Kitchenarf6Ne6h0UDXizsbMcOomQAkJFqLqHHAKY3H5R8p7cPQ52012-12-09Yupha Thai is definitely a "yuppy" in terms of being a great spot to go to. There are not too many places to eat near ASU Research Park, which is rig000
Hotel Indigo ScottsdaleVDtEMw1X397ViDlP7oErTw8Oy9-UwJQWffS0yOwPG6Ew42013-07-01I stayed here for one night while on a recent business trip! I wish I had discovered this place sooner.... I was pleasantly surprised! I never heard 000
Da VˆngxbVGTBSsXmvu56FTbXp7AwF6mQhKLdj_PEdxLvDYOm2Q52011-12-15I haven't had better pho anywhere in az. the large pho is enormous for the price. i usually go with my family and order a regular sized pho for myself000
Trader Joe'sHzI7nVlXJQJR3GO1KXYxlAcMmQsFyrYBv6hIE6NffqZQ52011-01-03Trader Joe's always goes above and beyond in all of their services. The food is fresh and delicious, the prices reasonable and the people are great. 000
Beaver Choice18fIpXUbcm9k6Pmtkbf0aA3gIfcQq5KxAegwCPXc83cQ42011-04-21So I went here tonight with a friend. I was really excited and nervous to try this place after reading the reviews. So you walk in and walk up to the110
Some BurrosOqogqje3RKspPwVcREfsXAGnqNc74So5Pc8C3hkA2hCg52009-07-10Came here w/ the hubster's. I've actually been craving this for some time now. The pollo fundido is great! So goooooood! Its a pretty big portion. The021
Superstition Ranch MarketB1xnRb2j_iW2Ws0u1B0FNwEOLRikjQxTIpXB4aV1hbPQ52012-01-05Great place to shop, buy what you will use within a few days.000
Fuego TacosJ6nrjjCjXc-hnRpZZPrLnQA99dyhEqcd_yXKPfBWeZHA32011-08-18I went to a late lunch on a Saturday and the Esplanade area was quite dead (I'm surprised because in the old days ('98-'99), I remember it to be prett000
The Woodshed#NAME?lsp7p2NuC5MX4_iuch3_OA12012-06-17We only went here because it has been a traditional Father's Day event with friends. We decided to join them for the 1st time......really...we will n010
Rosati's PizzaLd4Qg2Du0S3ulcdDCdm7JgSEDJTWEzMdqp7UsS1W3KXw32012-10-24First of all, let me just say their food is fantastic. I love their pizza. I love their salads. I love the cheesy garlic bread and their chicken parm.100
Sekai Sushi8TB8vM1H_SuEK2hS-5wu7gTDlgqAxf268QOw-OUk2Urw22012-05-02I am sorry to say people of Mesa you must have pretty low standards if this is the best sushi bar in Mesa. I went there last night and I really did no020
D'Vine Bistro & Wine BarJvHH1Z84UJ1P5T9uIxEnyQrT4ycOjlrKefSAcjoQga5g42012-04-12Love the atmosphere and fantastic happy hour! Favorite spot in Mesa:)010
Scottsdale StadiumeAYq_HT_gbD_ECgIWn3GoAMt3dPqOlnlGyVCftCcokmg42012-03-27Ignoring the fact that Scottsdale Stadium is a bit overpriced these days for Spring Training Giants tickets, its fun. Its basically one big party (in 030
Thai House#NAME?fczQCSmaWF78toLEmb0Zsw42008-07-21Damn... Helen Y beat me to the punch and got the FTR for this place! Oh well, I will say that she did a great job with her review - I think I was Tha387
Jalape–o Inferno Bistro MexicanoVRiSQiIfUnZdp0CxNMkLWg4nJ5ryQTcQKs8mCrgt8-BQ22011-04-05The dinner we had here was OK... nothing to rave about. The tortilla chips were very good as others have mentioned... a mix of corn and deep fried flo000
Caffe Boahi6a3fvAbtZq9jMIM8gkwQqa05pUVNapADHZXpHMPMeA32010-06-26Caffe Boa is an interesting jokester, so, it is interestingly hard to review it. I'll keep it short. I have gone here several times, and each time wit000
Golden ValleyZYEAmRpYHxJYcbIv-c7S2wgg_OKjOAl_vVmdh5ZETuiw32012-02-25Can I tell the difference between Uzbek cuisine and other Middle Eastern or Mediterranean cuisine? Nope. For all I know it's only a matter of where000
Canyon Cafegi9hLYOPk_fbvOr2mCHu7gnH9OZEGfgseWjC5_IPGCXw52010-08-09Everything about this place is wonderful!! I love the huge windows and outdoor patio! Gorgeous! Their food is amazing everything from the chips (there001
Panda Expressr52OE-CfRoJQyjBtn0vHIQfMyKbyYY9Poy9B_1QZPKcg12010-05-31My young children love Panda Express orange chicken. They eat it 2-4 times a month. We were at the mall on a Saturday afternoon and stopped into the f000
Gordon Biersch Brewery RestaurantpfPFWY5SXQEEnlVJbFaNqAnKaR5Z9Qmqc4RsakLLX_7w32010-03-29It's very hard for me to enjoy a house brewed schwarzbier that, to me, tastes more like Bud Light with a hint of acrid smoke flavor than what I consid243
Chili's Grill & Bar42EOZ0KMF4wU1Sz7oeLfpAAfyzIHPy5zds_mqf2Jdc9g32011-02-07I love Chili's. My husband and I always go for the 2 for $20 deal at whatever Chili's location we may be, but this location seemed to skimp out on the000
Beckett's TablelNLiQx1zi-ctta6v4LLhXwGJwbccjXgoRPbNuWcNKYXA52012-01-29Beckett's Table is a fantastic restaurant for people who want great food, great wine, and great service. My wife and I dined there with a couple of fr000
My Big Fat Greek RestaurantIuSys52QuyTxGv3HLFKBSw1gY1N3pkxTzh7kK4BxANyw42011-05-07I hated Greek food, until I tried this place. My "health nut" girlfriend had to drag me to this place, kicking and screaming. After all, my long ago233
Goldmans Deli6DggWM9rgzC_mIo4THFpMAPKZvqm3IeWiWBYoDDoEG4w52012-09-02Traveled in from the east coast so I got to Arizona very early in the day. I needed to kill some time before I could check into my hotel room so I en000
Macayo's Depot Cantina98nvcyGhtHlKO8pDlOcCsAbZFRqP7s0Vszxeu8_IwYow32008-03-21I finally ate lunch here after not being able to get decent parking for Quiznos on Mill Ave. My coworker and I were starving and needed a place to sh023
Rayner's Chocolate & Coffee ShopGCdNDjutQWsT-qaYwW0zxwM28A6JPQFBJnRBCfODe8IA42013-05-15Cute bakery/coffee shop hidden in a little plaza on 51st Ave off of Thunderbird Rd. Nice selection of unique baked goods, chocolates and coffee drinks010
Sushi Brokersup3ueFZ1xJh_ts6dVu3_0AhDlSSyDreM9xY4yQWPm54w22009-02-26--expensive for business lunch --servers very attentive, prompt --lacks nth-degree detail of a Japanese chef running things; rolls and standards are s433
The Vig Uptownrib7dXO863eL5VGUDsot8guQCk37gNl1bEmkjAv6_kAw42011-04-17My meal was great; the decor / layout is great also, with a lovely patio out back. The only downsides are parking, and the fact that the entrance is a010
Lo-Lo's Chicken & WafflesIlFoK4meMZ7Ws4enESzeTQEacK6XwZjsTD6QYSIRlJ7Q52008-07-14At first most of my noobie friends are very skeptical about the fusion of Chicken and Waffles. but after taking them to this place and experiencing f232
Shoe CarnivalYhlJA_CuoZlK4FIJUHlCnw_PzSNcfrCjeBxSLXRoMmgQ22010-05-17I had a $5 coupon in the mail so I was like what the heck. And is it next to Home Goods (one of my favie home decoration stores). I got to the store i210
My Big Fat Greek RestaurantQe0FO565tGfTxb7QtNCVwg2vl3MXKr8iQOWTNse5kgdw32008-04-03Nice menu selection; food was tasty. Good atmosphere. Wished they had a restaurant in the LA area.010
Casey Moore's Oyster HouseR7ZJPW4qEXuqI41aaWmO0ArLtl8ZkDX5vH5nAx9C3q5Q42009-04-02This is a fun place for appetizers and drinks if it is not too crowded and the temperature is just right outside. Otherwise the inside gets way too p121
Q to U BBQIJxqQwzJjAURPBAB_-iOAAMSgZpSWlf8T2H_46OWNgCQ52011-09-08Really enjoyed the Ribs and fries, I came with friends that really like BBQ, they agree, the ribs were terrific! I am sure we will be going back to Q111
Lightning LubekezCWAz6MO1wKwXB_DK-3QbwmXfjwrogAaGqV33kSVpQ32013-08-24$115 for an oil change and two air filters for my civic. I must've had a really long day or she had magical powers and made me forget I could simply c011
Athens GyrosaAgVzZU2b0YbYGi4byeI6wL8_GwFxxtGSYR2F_dglpSg42013-08-17Great food nice service. The girl that worked up front introduced herself to the other patrons that were there and asked them how the food was but no000
Metro Light RaillG8Swugg_DQxY3NgT_BEigLqgGgWi3FLHBViX9tmZ9sw32011-10-31I just wish that this stupid HUGE metropolis could have more LIGHT RAIL connections!! compared to the circus you have to stand in the buses, the LR is111
Oregano's Pizza Bistro7QvgM_LJi6SRp_GuOXPFZQfor16MiFS1M_8_cne6IbIw42013-02-04Big Delicious portions!000
Gallo BlancogULD5qz_CQI9clPWh2FNHAZ02XdD0muEz2FFQKPERMYQ52013-12-29Stopped in here one night right before Christmas. Short and sweet: Margaritas - very good (and huge by the way) Tacos - awesome Guacamole - exce222
Los Dos MolinosJcWhDcyNl3r_Tbeqiac15QGoymUzKqvET2QOZkIWZi9w42014-01-07We have a friend who said the salsa is way too hot. All I heard was "you must try Los Dos Molinos". We love spicy food and are always up to a challeng011
Nancy's Nail SalonZGo8c57MrzQrSN6R7zO1uQA9g7YnTtsSV-wEIo3HI1YQ42011-06-09Came here with my sister in law she had a coupon for a 27.99 mani/ spa pedi. The staff was friendly they have a tv and plenty of magazines to look thr010
Changing Hands Bookstore1xzMe1EEwhF23RNh3InKkQfPHLPrymsyb6WSFFKoMrTQ52010-10-26This not-so-little bookstore has it all... new and used books, a unique gift section, book signings and events, wonderful staff and a cool, organized,001
Tortilla FishOmSYYxZskG9BeRMwb5DltwMxO7EY766jVoFEZzkpwmOQ22013-10-06My experience wasn't bad, just not up to the hype of all the other reviews. I tried the shrimp, fish, campechana and machaca tacos. The shrimp tacos w000
Pet Club0LvO1yc-52fJ6vIHaFVdAwLXOhR4ZUULSbBNztxYZ2dQ22013-07-16That awkward moment when local competitors come write negative reviews about a store and then direct traffic to their own store....011
Taste of TopsJ2lGBvJOcuhmauWs3rgMSgaIAjAU-6NH583EkQ6E9KRw42009-10-09Okay, in interest of full disclosure, I literally live around the corner and across the street from Tops Liqour and have been waiting forever for this111
Carolina's Mexican FoodN6eg6Jc_mL_XHMGmw6GElwcbxUyCUMjkWAs1h4auYeAw42012-01-31If you're looking for real Mexican in a hurry this is your place. This is one of places ill always bring out of town guests who can't find good Mexica001
Super L Ranch MarketcK3J7FAqruLZM_Y5J29Q8Qz06IHGXI_ofBc2DkAbCgnA52011-05-09HOLY CRAP THEY HAVE FROZEN XIAOLONGBAO. :) These delicious little bites of porky, soupy dumpling heaven have eluded me since I first tasted them in 221
Salt CellarIXGX_Lk2NgCH-0OQNcGMpQE4HbTIHd9PVjUnEKpysaLw52011-10-04My experience here was absolutely amazing. My boyfriend and I had reservations for 7:30 pm on a Saturday night and the service was amazing and the fo021
Rosita's Placef_yQqlsim0S9YAIIYFvR5Q7nlZJW84Adt6oYn2shnn_g32013-05-30The food here is delicios, but it takes forever. From the time I ordered to when I was served 25minutes. Come only if you have time to spare to sit an000
Matador Restaurantx927gFqVNPSOPwNrKqPmmQnyHh14Vb9S269-kGKaUelg42011-08-09I've eaten at Matador almost once a month for about15 years. I won't get into the logistics of others reviews. I give the higher than average star rat001
Hanny'sriZp_RIN28ld-U2Q5dhKhAGRgBu4K7GOb3354esp_xkg42010-06-08Food = 4 stars Place = 5 stars Service = 4 stars I REALLY like this place. It looks super classy inside and the deco on both floors is a333
Crust Pizza and Wine CaferTc3d_GYXyHuf_tQoED80gAOmdmYYSeLUstcN084_wMA12012-10-16I told my friend that I'd rather eat out of a vending machine, and he said.. "Yelp THAT!" I had the calamari app, the caprese salad and the eggplant210
Ocean Air9gLTx4HjE-NeSa3KTfGJJQK0U0Hp6rgXHrYCG4jpPT8w52013-09-01Thank you! Ocean Air came highly recommended and now I know why!! Excellent, fast, friendly service!!! Reasonably price AC maintenance and FAST respon000
Sleepy Dog Brewpub9gtyU7vjWUjddmFrT97swwFm0EXFwIfDQoIm9RgcAOKQ32013-04-06As a number of others have said, the beer is good with a good number of choices. The food is pretty good too. The biggest issue has been service. The000
unPhogettableyVK0x3_-o16ufBbIyqGJRwsWh4Tjwa8ch_rziHtTN9LA52013-08-27Always amazing service! Always amazing pho! Add veggies to a meat dish! The spring rolls A1 & A6 are the best in town!!! We are now here on a weekly b111
Paradise Valley Burger CompanybkZ67PfRlKLKl4x5mIFYSgff00OcqImnNYy-OvSgUZyw52013-11-04Best burgers in town! They don't skimp on quality or ingenuity.000
Hanny's4n_3G2Xux0stcgOUsrzYawev7D2jo5OUDeHf0dWoWlsQ22012-06-25Super disappointing, they won't take reservations and I wanted to make a reservation for 20 persons. I've been here many many times and love the food 002
Golden PandaikNpO72tj7uI5VTatHpoAA80OFMLRA0yW3sE4ciYg_vA12009-10-10Why oh why is it so hard to find good Chinese food in this town? The two behind the counter at this place are Chinese - please don't tell me you eat000
Breakfast ClubU_oJEB166nCeBNY-wqadxwAMYi-53cxstrCR5wqyY1KA52011-01-11O-M-Goodness! What luck to have eaten here for breakfast!! Huge portions served with fresh fruit slices or mixed berries. Great service and very nice000
Ulta Salon Cosmetics & Fragrance9e3MOWg4zrq_NOqKP3fMcQF6QsMoJdvtohlbnST-fDyQ42011-03-14I really like this store and have been going here for as long as they have been open. 18 or 19 years. It is always exciting to be rewarded for the pro110
Essence Bakery CafŽNkekoPY-4txUxkyoN_Tu4wDrWLhrK8WMZf7Jb-Oqc7ww52012-09-14Ok, I'm not sure I ever had this pastry combination, but it was clearly a great item. It was the Chocolate almond croissant. Usually those two varieti010
zpizzaUJEPSoO6yNnR8kdneDy0rgfSi-yrKtBD58h2vPxjNE1A42010-12-01We ordered 4 rusticas for delivery using their buy-one-get-one promo online. They had a great deal on rustica pizzas, but somewhere in the fine print 211
Kona GrillosYRF4FQe4cziGIXz33eQQgITFg65GtRDUb-0n460vNg42011-03-17I've eaten at Kona Grill twice in two days while doing business in the area. I had the Kona Burger and the Pepperoni Pizza. The burger was fantastic000
White Housexn2LkVHBuRZ_jAg-LIiQ4QwFweIWhv2fREZV_dYkz_1g42011-07-25It's been a while since I took part in the nightlife in Scottsdale, it's not my scene but I was invited to White House for a party so you know how tha354
Crowne Plaza Resort Hotel San Marcos Golf ResortbMKW11Cf1Zeu1zWkzDbtrQKt9NwDONle_mc0QHTud9jw12011-07-18Rating the golf course, horrible!! Thank goodness there was no one in front of us and we zipped around the course. They clearly stopped maintaining 000
Hon Machimu8Gst6LkzG5ahmolCH55gKucBnMrhalzxnD9AWrxwYQ52011-06-21Great place for sushi and tepan - period. Not the "high-end" places but a rock solid place with lots of variety and good prices.010
Bourbon Steak a Michael Mina RestaurantAA6QQUFGWWkZlbpat46OfQcEIeuU0-4fX0Y4qCUW3PwQ22008-12-01My husband, some friends and I went to this place for restaurant week. We all sampled different dishes to experience a range of items - the multi-flav012
Tempe's Front PorchJ71o5dOSoxoOhcR8NEo4OgR4Ax3btoJ6qLXhqq6J50VQ42014-01-06This is the front porch of Monti's, my boyfriend and I were pretty confused looking for it. It's outdoors with a bunch of heating lamps, be sure to s121
Joyride Taco HousepKe_ORPqaW0vfGyFkbxdHwxv9nUSKR5RqnkgD0tufTfA42013-12-02Tried this place tonight with my boo and I am definitely a fan. He loved his carne asada burrito and my enchiladas were super tasty. They are a littl000
LunardisfpjKqP8ONJ9rT8209thIQQ9itypHULqGyO42s3zNUzOQ52018-06-11This is the nicest grocery store in the city. I actually met my wife at this grocery store while shopping for avocados.6710

However, you really can’t see from the output that the new data type is INT. Let’s check this by adding one column that uses the pg_typeof function to the PostgreSQL solution to show the converted data type of the column stars.

SELECT business_name,
       review_id,
       user_id,
       CAST(stars AS INT) AS cast_stars,
       pg_typeof(CAST(stars AS INT)) AS cast_stars_type,
       review_date,
       review_text,
       funny,
       useful,
       cool
FROM yelp_reviews
WHERE stars <> '?';

As you can see from the output, the column stars is really cast as INT.

All required columns and the first 5 rows of the solution are shown

business_namereview_iduser_idcast_starscast_stars_typereview_datereview_textfunnyusefulcool
AutohausAZC4TSIEcazRay0qIRPeMAFgjlbPUcCRiXlMtarzi9sW5w5integer2011-06-27Autohaus is my main source for parts for an old Mercedes that has been in the family since new that I am restoring. The old beater is truly a labor of121
Citizen Public HouseZZ0paqUsSX-VJbfodTp1cQEeCWSGwMAPzwe_c1Aumd1w4integer2013-03-18First time in PHX. Friend recommended. Friendly waitstaff. They were understaffed and extremely busy, but we never knew. The short ribs were tende000
Otto Pizza & PastrypF6W5JOPBK6kOXTB58cYrwJG1Gd2mN2Qk7UpCqAUI-BQ5integer2013-03-14LOVE THIS PIZZA! This is now one of my favorite pizza places in phoenix area. My husband i walked into this cute family owned business and were greet000
Giant HamburgersQBddRcflAcXwE2qhsLVv7wT90ybanuLhAr0_s99GDeeg3integer2009-03-27ok, so I tried this place out based on other reviews. I had the cheeseburger with everything, some fries, and a chocolate shake. The burger was okay, 011
Tammie Coe CakesY8UMm_Ng9oEpJbIygoGbZQMWt24-6bfv_OHLKhwMQ0Tw3integer2008-08-25Overrated. The treats are tasty but certainly not the best I have ever had. I would have rated this a two star but the cakes and cookies are REALLY pr132

Example #2: Casting INT in Calculations

Let’s see another example where it’s necessary to cast INT to another numerical data type before the mathematical operation is performed.

This question by Airbnb is ideal for showcasing that.

Last Updated: January 2018

MediumID 9624

Find the average accommodates-to-beds ratio for shared rooms in each city. Sort your results by listing cities with the highest ratios first.

Go to the Question

Link to the question: https://platform.stratascratch.com/coding/9624-accommodates-to-bed-ratio

The question asks to calculate the average accommodates-to-beds ratio for shared rooms in each city and sort the output from the highest to the lowest-ratio city.

We will use the table airbnb_search_details.

Table: airbnb_search_details
Loading Dataset

Let’s not immediately jump to the question solution.

We’ll explore it step by step. The approach is to divide the column accommodates with the column beds to get accommodates-to-beds ratio. Explore the dataset and you’ll notice we’re dividing integers. As a result, the output will also be an integer.

Typically, ratios are shown as a decimal number. Because of this, we need to cast INT. It’s sufficient to cast only one integer.

Let’s translate all this into an SQL query.

SELECT city,
       CAST(accommodates AS FLOAT) / beds AS crowdness_ratio
FROM airbnb_search_details
WHERE room_type='Shared room'
GROUP BY city, crowdness_ratio
ORDER BY crowdness_ratio DESC;

PostgreSQL
Tables: airbnb_search_details

You have reached your daily limit for code executions on our blog.
Please login/register to execute more code.

Cool! So, the output shows different ratios for LA and NYC. The data conversion obviously succeeded, as we have two ratios shown as decimals.

All required columns and the first 5 rows of the solution are shown

cityavg_crowdness_ratio
LA1.6
NYC1.5

What would have happened if we ignored the need for casting?

SELECT city,
       accommodates / beds AS crowdness_ratio
FROM airbnb_search_details
WHERE room_type='Shared room'
GROUP BY city, crowdness_ratio
ORDER BY crowdness_ratio DESC;

Three rows would be exactly the same, but that’s only by chance, as the division returns a whole number in those cases.

However, the last two rows show different results from the previous output. Instead of 0.5 and 0.4, we have 0.

Why is that? Dividing integers truncates the result towards zero.

All required columns and the first 5 rows of the solution are shown

citycrowdness_ratio
LA4
NYC2
LA1
LA0
NYC0

So, in this first step, we already have incorrect results.

The error will be compounded when we write the final code solution, as we also need to calculate the average of these ratios. An average based on wrong values? It doesn’t sound promising!

Let’s return to our code, where we use CAST(). If I amend it like this, it becomes a question solution.

So, the only changes are:

  1. Using AVG() on the cast ratio calculation.
  2. Renaming the output column from crowdness_ratio to avg_crowdness_ratio.
  3. Removing the column crowdness_ratio from GROUP BY as this column is now aggregated.

SELECT city,
       AVG(CAST(accommodates AS FLOAT)/ CAST(beds AS FLOAT)) AS avg_crowdness_ratio
FROM airbnb_search_details
WHERE room_type='Shared room'
GROUP BY city
ORDER BY avg_crowdness_ratio DESC;

PostgreSQL
Go to the question on the platformTables: airbnb_search_details

You have reached your daily limit for code executions on our blog.
Please login/register to execute more code.

The output shows the average ratio for LA is 1.6, and for NYC, it’s 1.5.

All required columns and the first 5 rows of the solution are shown

cityavg_crowdness_ratio
LA1.6
NYC1.5

Now, the same code without casting looks like this.

SELECT city,
       AVG(accommodates / beds) AS avg_crowdness_ratio
FROM airbnb_search_details
WHERE room_type='Shared room'
GROUP BY city
ORDER BY avg_crowdness_ratio DESC;

The code calculates the LA ratio at 1.5 (wrong!) and NYC at 1.333 (again, wrong!). You see now why casting INT is important!

All required columns and the first 5 rows of the solution are shown

cityavg_crowdness_ratio
LA1.5
NYC1.33

Of course, the question can also be solved using CONVERT() in SQL Server.

SELECT city,
       AVG(CONVERT(FLOAT, accommodates)/ CONVERT(FLOAT, beds)) AS avg_crowdness_ratio
FROM airbnb_search_details
WHERE room_type='Shared room'
GROUP BY city
ORDER BY avg_crowdness_ratio DESC;

MSSQL
Go to the question on the platformTables: airbnb_search_details

You have reached your daily limit for code executions on our blog.
Please login/register to execute more code.

As expected, the output is the same as that of CAST().

All required columns and the first 5 rows of the solution are shown

cityavg_crowdness_ratio
LA1.6
NYC1.5

Handling NULL Values When Casting INT in SQL

When casting INT, the NULL values can be handled in two ways:

1. Implicitly: Let CAST() or CONVERT() handle it, which means they will automatically return NULL where there are NULL values.

2. Explicitly: You could use COALESCE() to check for NULL values and specify the value with which they’ll be replaced.

Example #3: Handling NULLs Implicitly

I’ll use this easy question by ESPN to show you how to handle NULLs.

EasyID 10184

Order all countries by the year they first participated in the Olympics.

Output the National Olympics Committee (NOC) name along with the desired year.

Sort records in ascending order by year, and alphabetically by NOC.

Go to the Question

Link to the question: https://platform.stratascratch.com/coding/10184-order-all-countries-by-the-year-they-first-participated-in-the-olympics

We’re given the table olympics_athletes_events

Table: olympics_athletes_events
Loading Dataset

Let’s imagine you need to cast the age column to INT. You would do it like this.

SELECT id,
       CAST(age AS INT) AS cast_age
FROM olympics_athletes_events;

PostgreSQL
Tables: olympics_athletes_events

You have reached your daily limit for code executions on our blog.
Please login/register to execute more code.

Since there are also NULLs in the age column, those values will be displayed as NULL despite casting.

All required columns and the first 5 rows of the solution are shown

idcast_age
3520
35394
2191828
11034526
5419326

Example #4: Handling NULLs Explicitly

But what if you’re moving data between systems, and the destination system requires the age data to be INT but also doesn’t accept NULLs in that column?

In that case, you should use COALESCE() with CAST().

The code below is similar to the previous one. However, I use COALESCE() to replace all NULLs with zeros.

SELECT id,
       COALESCE(CAST(age AS INT),0) AS cast_age
FROM olympics_athletes_events;

PostgreSQL
Tables: olympics_athletes_events

You have reached your daily limit for code executions on our blog.
Please login/register to execute more code.

If you compare the output with the previous one, you’ll see there are 0s where there were once NULLs.

All required columns and the first 5 rows of the solution are shown

idcast_age
35200
353940
2191828
11034526
5419326

Best Practices for Type Conversion in SQL

When casting data types, I recommend you stick to these four simple and common-sense rules.

Best Practices to Cast Int in Sql for Type Conversion

1. Using CAST() for Compatibility

As you already know, CAST() is part of the ANSI SQL standard. Stick to it if you plan to use SQL code across different RDBMSs, as they all support CAST().

If you write your code in SQL Server and use CONVERT(), you’ll have to rewrite it if you want to run it in another SQL flavor.

2. Handle NULLs Appropriately

Having NULLs in your dataset can lead to unexpected results or errors. For example, this can happen when doing arithmetic operations, aggregating data, filtering, or sorting data.

So, use the standard SQL function COALESCE() to provide default values for NULLs or ISNULL() in SQL Server and IFNULL() in MySQL.

3. Check the Conversion Result

Converting data types can result in errors or unexpected output. This is especially true when you write more complex queries.

Whenever you convert types, check the output and validate if this is the expected result. Also, test it on edge cases to see if it covers possible scenarios that are maybe not present in the current data.

4. Understand Database Specifics

Whatever SQL database you use, read its documentation. All the specific data type conversion functions, their default behaviors, and conversion quirks will be explained there.

For example, PostgreSQL allows using :: instead of CAST(). On the other hand, in SQL Server you have an option of using CONVERT(), which might be useful when wanting more control over date and time formats.

Conclusion

Today, we discussed one specific data type conversion: from and to INT. This conversion works similarly to any other data type conversion in SQL, as it most typically involves the standard SQL function CAST().

I’ve shown you how this works in several practical examples. However, casting INT in SQL is technically relatively simple. Where this gets complicated is recognizing that the casting is needed and deciding which data type to choose. We discussed different data types to help you with this.

But all this can’t be learned only by reading an article, no matter how good it is. So, your next step is to practice by solving at least several of many coding interview questions from our platform that require data type casting.

This is an important step in avoiding data handling errors that could occur by not casting data types or casting them to inadequate data types.

Share