Showing posts with label int. Show all posts
Showing posts with label int. Show all posts

Tuesday, March 27, 2012

Boolean ? in SQL (2005) table

I was wondering what should be used for a yes/no/ entry identifier . Should it be a simple int , tinyint , or uniqueidentifier?

Thank you

The bit data type is for values that can be either 0 or 1, such as No/Yes or False/True.|||The way you have written your answer suggests that 0 =yes and 1 = no which goes against my common sence. Could you clarify. I am sorry if this seams a bit picky.|||

No problem:

0 --> No, False

1 --> Yes, True

Boolean ? in SQL (2005) table

I was wondering what should be used for a yes/no/ entry identifier . Should it be a simple int , tinyint , or uniqueidentifier?

Thank you

The bit data type is for values that can be either 0 or 1, such as No/Yes or False/True.|||The way you have written your answer suggests that 0 =yes and 1 = no which goes against my common sence. Could you clarify. I am sorry if this seams a bit picky.|||

No problem:

0 --> No, False

1 --> Yes, True

sql

Sunday, February 12, 2012

Bitwise question -

I am new to bitwise thing in MSSQL.

Let's suppose there's a table of favorite foods

insert int fav_foods(food_name,bitwiseVal)
values('Pasta',1)

insert int fav_foods(food_name,bitwiseVal)
values('Chicken',2)

insert int fav_foods(food_name,bitwiseVal)
values('Beef',4)

insert int fav_foods(food_name,bitwiseVal)
values('Fish',8)

insert int fav_foods(food_name,bitwiseVal)
values('Pork',16)

How do I write query to find people who selected more than one item and
selected items from "Pasta, Chicken, Beef, Pork"(but not fish)?
I hope my question is not confusing....Bostonasian wrote:
> I am new to bitwise thing in MSSQL.
> Let's suppose there's a table of favorite foods
> insert int fav_foods(food_name,bitwiseVal)
> values('Pasta',1)
> insert int fav_foods(food_name,bitwiseVal)
> values('Chicken',2)
> insert int fav_foods(food_name,bitwiseVal)
> values('Beef',4)
> insert int fav_foods(food_name,bitwiseVal)
> values('Fish',8)
> insert int fav_foods(food_name,bitwiseVal)
> values('Pork',16)
> How do I write query to find people who selected more than one item and
> selected items from "Pasta, Chicken, Beef, Pork"(but not fish)?
> I hope my question is not confusing....

Your question isn't confusing but your design decision is. Why use
bitwise on something like this? If you were to use proper table design
this query would be trivial (and fast).

Zach|||I tried to simply the example as much as possible, that's probably why
it didn't look that neccesary to build table like this.

I actually have survey data. Survey answer includes text, single select
multiple choice and multi-select multiple choice.

In answered data table, I currently have schema like following :

customer | question_id | answer
---------------
John | 1 | Pasta
John | 1 | Beef
John | 1 | Chicken
John | 1 | Pork

And I've got 2.4 million customers to manage, so I thought it'd save
some rows by using bitwise to reduce row numbers to one.|||Bostonasian wrote:
> I tried to simply the example as much as possible, that's probably why
> it didn't look that neccesary to build table like this.
> I actually have survey data. Survey answer includes text, single select
> multiple choice and multi-select multiple choice.
> In answered data table, I currently have schema like following :
> customer | question_id | answer
> ---------------
> John | 1 | Pasta
> John | 1 | Beef
> John | 1 | Chicken
> John | 1 | Pork
> And I've got 2.4 million customers to manage, so I thought it'd save
> some rows by using bitwise to reduce row numbers to one.

What you save in rows (i.e. disk space, which is cheap), you'll likely
lose in readability, mainainability, performance and standardization.
Search out one of Joe Celko's rants about thinking like a procedural
programmer and not a SQL/set based programmer because I think that's the
problem here.

Zach|||> And I've got 2.4 million customers to manage, so I thought it'd save
> some rows by using bitwise to reduce row numbers to one.

I'll bet that disk space is much cheaper than the cost of the time you'll
spend fixing up a kludge like that :-)

Try this:

CREATE TABLE Foods (customer_id INTEGER NOT NULL REFERENCES Customers
(customer_id), food INTEGER NOT NULL REFERENCES Foods (food), PRIMARY KEY
(customer_id, food))

SELECT customer_id
FROM Foods
WHERE food IN (1,2,3,4,5) /* Pasta,Chicken,Beef,Pork,Fish */
GROUP BY customer_id
HAVING COUNT(CASE WHEN food IN (1,2,3,4) THEN 1 END) = COUNT(*)
/* Everything except fish */

--
David Portas
SQL Server MVP
--|||Bostonasian (axkixx@.gmail.com) writes:
> I am new to bitwise thing in MSSQL.
> Let's suppose there's a table of favorite foods
> insert int fav_foods(food_name,bitwiseVal)
> values('Pasta',1)
> insert int fav_foods(food_name,bitwiseVal)
> values('Chicken',2)
> insert int fav_foods(food_name,bitwiseVal)
> values('Beef',4)
> insert int fav_foods(food_name,bitwiseVal)
> values('Fish',8)
> insert int fav_foods(food_name,bitwiseVal)
> values('Pork',16)
> How do I write query to find people who selected more than one item and
> selected items from "Pasta, Chicken, Beef, Pork"(but not fish)?
> I hope my question is not confusing....

SELECT *
FROM tbl
WHERE fav_food & (SELECT SUM(bitwiseVal)
FROM fav_foods
WHERE food_name IN ('Pasta', 'Chicken', 'Beef', 'Pork'))

But as pointed out by others, this is a poor design. You may
save disk space, but if you need to find all that selected Chicken,
you will find that you cannot have an index on bit in an integer
column, so you get awful performance.

Look at David's query, and use that instead of the above.

--
Erland Sommarskog, SQL Server MVP, esquel@.sommarskog.se

Books Online for SQL Server SP3 at
http://www.microsoft.com/sql/techin.../2000/books.asp|||Bostonasian wrote:
> I tried to simply the example as much as possible, that's probably why
> it didn't look that neccesary to build table like this.
> I actually have survey data. Survey answer includes text, single select
> multiple choice and multi-select multiple choice.
> In answered data table, I currently have schema like following :
> customer | question_id | answer
> ---------------
> John | 1 | Pasta
> John | 1 | Beef
> John | 1 | Chicken
> John | 1 | Pork
> And I've got 2.4 million customers to manage, so I thought it'd save
> some rows by using bitwise to reduce row numbers to one.

Hi Bostonasian,

There is no need to denormalize or use bitwise operations for this. IMO,
bitwise operations are not suitable for this problem.

The database does not have to grow very fast. If you normalize all the
way through, you would get a Customers (reference) table, a Questions
(reference) table and a Answers (reference) table. All these reference
tables can have short keys, which you use in your CustomerAnswers (data)
table. If you have fewer than 64000 customers, fewer than 256 questions
and fewer than 256 (fixed) answers per question, then each row in
CustomerAnswers would be just 2+1+1 = 4 bytes (excluding the free format
text answers).

Your schema could look something like this:
CREATE TABLE Customers(CustomerID smallint PRIMARY KEY, Name
nvarchar(100))
CREATE TABLE Questions(QuestionID tinyint PRIMARY KEY, Question
nvarchar(3000))
CREATE TABLE Answers (QuestionID tinyint, AnswerID tinyint, Answer
nvarchar(200),PRIMARY KEY (QuestionID,AnswerID))

CREATE TABLE CustomerAnswers
(CustomerID smallint REFERENCES Customers
,QuestionID tinyint REFERENCES Questions
,AnswerID tinyint
,TextAnswer nvarchar(2000)
,PRIMARY KEY (CustomerID,QuestionID,AnswerID)
,FOREIGN KEY (QuestionID,AnswerID) REFERENCES Answers
)

Hope this helps,
Gert-Jan

bitwise AND with Char column

based on BOL, bitwise AND operator operates only on integer data type
category (int, smallint, tinyint). but i have a char(4) column which
stores integers (disregard the db design issue) which produces the
same/correct results after using bitwise AND with another integer.
does this mean SQL server does the conversion itself?SQL Server will convert a value stored in the CHAR datatype into an INTEGER
because an INTEGER has a high
Data Type Precedence
"joeycalisay" <joeycalisay@.gmail.com> wrote in message
news:1131435508.269803.57870@.o13g2000cwo.googlegroups.com...
> based on BOL, bitwise AND operator operates only on integer data type
> category (int, smallint, tinyint). but i have a char(4) column which
> stores integers (disregard the db design issue) which produces the
> same/correct results after using bitwise AND with another integer.
> does this mean SQL server does the conversion itself?
>|||thanks a lot sir!|||Implicit conversion is at work here and that's potentially bad news.
Implicit conversions are to be avoided where possible because of their
potential to break unexpectedly under schema or code changes or even as
a result of service packs or version upgrades. Obviously a poor design
is at fault in your example but if you must accommodate it then I would
use CASE expressions:
CASE WHEN col1 = '1' AND col2 = '1' THEN 1 ELSE 0 END
David Portas
SQL Server MVP
--|||thanks for the input sir david particularly on the point of it being
breakable. poor design - yeah, i hated it when i saw it, wish i had
the time to revise it but they are at code freeze

BIT-Wise Aggregation

Hi,

I have the following three tables :
Account (Id int, AccountName nvarchar(25))
Role (id int, Rights int)
AccountRole (AccountID, RoleID)

In Role table - Rights Column is a bit map where in each bit would refer to access to a method.
One account can be associated with multiple roles - AccountRole table is used for representing the N:N relation.

I want to develop a store procedure - which would return all AccountName and their Consolidated Rights.
Basically I want to do a BitWise OR operation for all the Rights in the Aggregation instead of the SUM as shown in the following statement.

SELECT Account.Name, SUM(Role.Rights) FROM Account WITH (NOLOCK)
JOIN RoleAccount ON RoleAccount.AccountID = Account.Id
JOIN Role ON RoleAccount.RoleId = Role.Id
GROUP BY Account.Name

Thanks,
Loonysan

Here is code that shows a trick. The idea is to break each "rights mask" into a series of rows representing the separate bit values. These can be recombined with a Sum(distinct) across the roles owned by each account.

To make this work, you need a table that has one row for each bit position. My example shows a subset of bits built using a union. There is a system table called spt_values that holds a bunch of useful values used by system stored procedures. It contains rows for each bit position and would work with this application.

Drop Table #AccountRoles

Drop Table #Account

Drop Table #Role

go

Create Table #Account(

account_id int Not Null Identity( 1000, 100 ),

account_name varchar(100) Not Null

)

Create Table #Role(

role_id int Not Null Identity( 100, 1 ),

role_name varchar(100) Not Null,

rights int Not Null

)

Create Table #AccountRoles(

account_id int Not Null,

role_id int Not Null

)

go

Insert #Account values( 'Fred' )

Insert #Account values( 'Barney' )

Insert #Account values( 'Wilma' )

Insert #Account values( 'Betty' )

go

Select * from #Account

go

Insert #Role values ( 'Only 1', 1 )

Insert #Role values ( 'OneThree', 5 )

Insert #Role values ( 'JustTwo', 2 )

Insert #Role values ( 'All', 7 )

go

Select * from #Role

Insert #AccountRoles values ( 1100, 100 )

Insert #AccountRoles values ( 1100, 102 )

Insert #AccountRoles values ( 1200, 100 )

Insert #AccountRoles values ( 1200, 101 )

Insert #AccountRoles values ( 1300, 101 )

Insert #AccountRoles values ( 1300, 103 )

go

Select acc.account_id,

acc.account_name,

Sum(Distinct right_explode.single_right )

From #Account acc

Left Join #AccountRoles acr

On acr.account_id = acc.account_id

Join (

Select role_id,

bitposition,

rights & bitposition single_right

From #Roles

Cross Join

(

Select 1 as bitposition

Union

Select 2 as bitposition

Union

Select 4 as bitposition

Union

Select 8 as bitposition

Union

Select 16 as bitposition

) as bits

) right_explode

On right_explode.role_id = acr.role_id

Group

By acc.Account_Id,

acc.Account_Name

Order

By acc.Account_Name

Another approach would be to make a function that computed the bit-wise Or for a single account. This could be done using a local variable and a Select statement. This is not as good a solution.

Declare @.bitsum int

Select @.bitsum = bitsum | rights

From #AccountRoles ar

Join #Role r

On r.role_id = ar.role_id

Where ar.account_id = @.account

return @.bitsum|||

It works:

create table Account (Id int, AccountName nvarchar(25));

create table Role (id int, Rights int);

create table AccountRole (AccountID int, RoleID int);

insert into account values (1, 'DEMO');

insert into account values (2, 'TEST');

insert into role values (1, 125);

insert into role values (2, 225);

insert into AccountRole values (1, 1);

insert into AccountRole values (2, 1);

insert into AccountRole values (2, 2);

alter function f_or(@.acc_id int) returns int

begin

declare @.right int,

@.result int;

set @.result = 0

declare lcursor cursor for select rights from Role R, AccountRole AR where R.id = AR.roleid and AccountId = @.acc_id;

open lcursor;

fetch lcursor into @.right;

while @.@.FETCH_STATUS = 0 begin

set @.result = @.result | @.right

fetch lcursor into @.right

end

close lcursor;

return @.result;

end

go

select AccountName, dbo.f_or(id) 'Rights' from account

|||

Why do you think the second approach is not a good solution?

Thanks,
Loonysan

|||

If you only need to get the rights for a single Account, then the approach would be fine. However, in a set-wise report, my guess is that it would perform much worse as you are producing a new query for each Account instead of joining the tables in.

I only sketched what the function would look like. Can you complete the function or do you need more code? If you didn't simplify your tables or the problem, in a major way, for the sake of the post it should be easy enough to try both methods and weigh the advantages.

Friday, February 10, 2012

Bit mask issues...

With this clause:
where
CAST(substring(Column,1,1) as int) & 128 > 0
--
I try to find result where first bit is on.
Is there a better way to write this to speed up ?
Any help much appreciated.
Regards.
Fabri
-Mandrake "A Poma', c'hai 'na faccia...!"
-Pomata "S, se ce n'avevo due gi stavo all'universit... sotto
spirito!"Best get rid of the bit mask column and store the data as separate
attributes or rows. Bit maps are a poor and very inefficient way to
store data.
David Portas
SQL Server MVP
--|||David Portas wrote:
> Best get rid of the bit mask column and store the data as separate
> attributes or rows. Bit maps are a poor and very inefficient way to
> store data.
David, you are right.
But what about when you inherit a large data with these schema?
Do you think, also I'll try to migrate before or later, I can write that
where clause better?
I add that <column> is binary data type.
Regards.
Fabri
-Mandrake "A Poma', c'hai 'na faccia...!"
-Pomata "S, se ce n'avevo due gi stavo all'universit... sotto
spirito!"|||I'd suggest adding a table to store extracted relevant values from that
"overloaded" column. That way the old table remains intact and you gain a ne
w
relation to help you with your queries.
The only change to the old table would be a trigger to help propagate those
values to the new table (for inserted, updated, and deleted rows
respectively).
ML|||>> <column> is binary data type.<<
Quit writing assembly language in SQL.
Create a proper 1NF table. Put each attrivute in its own column, with
appropriate constraints. When you do this, you will probably find that
the data is very dirty. Drop the old table.
Fire the moron that wrote this code. This will improve future data
quality and make programming much easier.|||Firing morons just helps problems migrate somewhere else.
ML|||--CELKO-- wrote:
You are "that" CELKO ? 0__0

> Quit writing assembly language in SQL.
lol

> Create a proper 1NF table.
What does it mean 1NF?

> Fire the moron that wrote this code.
lol...even if I don't know what moron means I can try to figure it
out..:-)))
Regards.
Fabri
-Mandrake "A Poma', c'hai 'na faccia...!"
-Pomata "S, se ce n'avevo due gi stavo all'universit... sotto
spirito!"|||>> Firing morons just helps problems migrate somewhere else. <<
Operative word: "somewhere else" :) As I used to remind people at teh
last university I taught, I don't teach ethics or morals.|||>> You are "that" CELKO ? <<
Eat just one little baby and everyone remembers your name!
First normal form. It means that each column holds one and only one
scalara (atomic) value; not a list, not an array, not a sub-table. Any
book on RDBMS will have a formal definition.
person stupida|||--CELKO-- wrote:
>
> Eat just one little baby and everyone remembers your name!
CELKO, can I use this as signature?
Fabri
(Eat just one little baby and everyone remembers your name! |CELKO|)

Bit Field vs. Integer with Nulls

If I have a field where 99.9% of the time the answer is going to be "No", would I be better, in terms of disk space, using:

A bit field

OR

A tiny int field, with a NULL for the 99.9% that are "NO", and a 1 for those that are "YES".

I'm using SQL Server 7.0.

My application developer has no preference.

Thanks.How much data are we talking about?

Also What is the field for?

Do you have to display the data?

I'd go with...

CREATE TABLE myTable99(Col1 char(3) DEFAULT('NO') CHECK(Col1 IN ('NO','YES')))|||Roughly 8000 records a month. The field is used to identify those records that are going to be non-billable, which is a very small percentage of the time.

The field itself will never appear on any report; it will determine if the particular record should appear on the standard report, or if it will be moved to a special report.|||Brett dude! You'd seriously store "No" and "Yes" in the database?

Excesive verbosity!

"Y" or "N", or 1 or 0 thank you!

I don't believe that a single bit field is going to take any less space than a smallint. I think you have to have several bit fields grouped in your table to realize any space savings.|||Yo,

Blind dude

You'd seriously prefer to perform conversions for display purposes for only 8k rows a month?

SELECT CASE WHEN Col1 = 1 THEN 'YES' WHEN Col1 = 0 THEN 'NO' END

This is like using a surrogate...no thanks

So, you're saving 16k a month....let's through a party...